设置多个style.background值 [英] Setting multiple style.background values

查看:128
本文介绍了设置多个style.background值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的背景中使用渐变,并且要跨平台我想设置背景与供应商前缀:

I want to use gradients in my background and to be cross-platform I would like to set background with vendor prefixes:

background: -webkit-linear-gradient(red, blue);
background: -o-linear-gradient(red, blue);
background: -moz-linear-gradient(red, blue);
background: linear-gradient(red, blue);

如何设置多个 style.background HTMLElement 上,使用Javascript支持供应商前缀?

How can I set multiple style.background's on a HTMLElement, using Javascript to support the vendor prefixes?

更新:我不希望使用jQuery或任何其他外部库。

Update: I wish not to use jQuery or any other external library.

推荐答案

我认为只有你真正的选择是清除属性,它,然后重复设置它,直到它不再有这个值,如下:

I think just about your only real option is to clear the property, grab the value after clearing it, then repeatedly set it until it no longer has that value, like this:

function setPrefixedValue(elm, prop, value) {
    var prefixes = ['-moz-', '-webkit-', '-o-', '-ms-', '-khtml-'];
    var i, v, starting;

    // Clear
    elm.style[prop] = "";
    starting = elm.style[prop];

    // Try raw first
    try {
        elm.style[prop] = value;
        if (elm.style[prop] !== starting) {
            console.log("No prefix");
            return;
        }
    }
    catch (e) {
    }

    // Try prefixes
    for (i = 0; i < prefixes.length; ++i) {
        v = prefixes[i] + value;
        try {
            elm.style[prop] = v;
            if (elm.style[prop] !== starting) {
                console.log("Prefix: " + prefixes[i]);
                return;
            }
        }
        catch (e2) {
        }
    }

    console.log("Didn't find prefix");
}

// Usage
setPrefixedValue(someElement, "background", "linear-gradient(red, blue)");

Live Example | 来源

注意:我测试了各种版本的Chrome,Firefox,Opera和IE。我没有找到一个浏览器,似乎支持 linear-gradient 值,但需要一个前缀。最近的Chrome和Firefox;歌剧12.15;和IE10都支持它没有任何前缀; Opera 10.62,IE8和IE9不支持它前缀或不是。 (对于IE8和9,我想你需要使用一个过滤器。)

Side note: I tested various versions of Chrome, Firefox, Opera, and IE. I didn't find a browser that appeared to support that linear-gradient value, but required a prefix. Recent Chrome and Firefox; Opera 12.15; and IE10 all support it without any prefix; Opera 10.62, IE8, and IE9 didn't support it either prefixed or not. (For IE8 and 9, I think you need to use a filter instead.)

这篇关于设置多个style.background值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆