如何使用javascript设置CSS3过渡?

时间:2012-01-05 12:08:16

标签: javascript css3

如何使用javascript设置CSS(我无法访问CSS文件)?

#fade div {
  -webkit-transition: opacity 1s;
  -moz-transition: opacity 1s;
  -o-transition: opacity 1s;
  -ms-transition: opacity 1s;       
  transition: opacity 1s;
  opacity: 0;
  position: absolute;
  height: 500px;
  width: 960px;
}

例如:

document.getElementById('fade').HOW-TO-TYPE-webkit-transition = 'opacity 1s';

6 个答案:

答案 0 :(得分:29)

你应该看一下:http://www.javascriptkit.com/javatutors/setcss3properties.shtml

如您所见,使用“ - ”设置CSS属性只会导致下一个字符为大写:

document.getElementById('fade').style.WebkitTransition = 'opacity 1s';
document.getElementById('fade').style.MozTransition = 'opacity 1s';

答案 1 :(得分:6)

var vendors = [
    '-webkit-',
    '-o-',
    '-moz-',
    '-ms-',
    ''
];

function toCamelCase(str) {
    return str.toLowerCase().replace(/(\-[a-z])/g, function($1) {
        return $1.toUpperCase().replace('-', '');
    });
}

function setCss3Style(el, prop, val) {
    vendors.forEach(function(vendor) {
        var property = toCamelCase(vendor + prop);

        if(p in el.style) {
            el.style[p] = val;
        }
    });
}

用法:

setCss3Style(someElement, 'transition', 'opacity 1s');

这是live demo

答案 2 :(得分:6)

你应该像这样使用camelCase表示法:

document.getElementById('fade').style.webkitTransition = 'opacity 1s';

就像每个由多个单词和连字符分隔的属性组合(例如css background-position变为js backgroundPosition

可能目前并非所有浏览器都在涉及浏览器特定前缀的属性中使用此表示法,因此有些浏览器如firefox仍然接受Moz而不是moz(请参阅https://bugzilla.mozilla.org/show_bug.cgi?id=607381)< / p>

答案 3 :(得分:1)

第一个例子:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style>
        #square {
            width: 100px;
            height: 100px;
            border-radius: 5px;
            background-color: red;
        }
    </style>
</head>
<body>
    <div id="square"></div>
    <script>
        var CSS3Error = function () {
            return {type: "Erro", message: "Classe não iniciada!"}
        }

        function CSS3(_property, _values) {
            var prefix = ["", "o", "ms", "moz", "khtml", "webkit"], values = _values, started = false, property = _property, prefixKey = 0, propertyValues = "";

            this.init = function () {
                if (!started) { 
                    started = true;

                    for (var i = 0, length = prefix.length; i < length; i++) {
                        prefix[i] += property;

                        if (prefix[i] in element.style) {
                            prefixKey = i;
                            break;
                        }
                    }

                    transitions();
                }
            }

            this.changeStyle = function (element) {
                if (started)
                    element.style[prefix[prefixKey]] = propertyValues;
                else
                    throw new CSS3Error();
            }

            this.setValues = function (value) {
                values = value;
                transitions();
            }

            function transitions() {
                propertyValues = "";

                if (property == "transition") {
                    for (var i = 0, length = values.length; i < length; i++) {
                        propertyValues += values[i];

                        if (i < length - 1)
                            propertyValues += ",";
                    }
                }
                else
                    propertyValues = values;
            }
        };

        function Method(_method)
        {
            var method = _method;

            this.delay = function () {
                var effect;

                setInterval(function () {
                    if (!effect) {
                        effect = method;
                        effect();
                    }
                    else
                        clearInterval(this);
                }, 2000);
            }
        }

        var property1 = new CSS3("border-radius", "20px"), property2 = new CSS3("transition", ["all 3s"]), property3 = new CSS3("sdads", "dasds"), element = document.querySelector("#square");

        new Method(function () {
            try {
                property1.init();
                property1.changeStyle(element);
                property2.init();
                property2.changeStyle(element);
            }
            catch(exception) {
                alert(exception instanceof CSS3Error ? exception.type + ": " + exception.message : exception.message)
            }
        }).delay();
    </script>
</body>
</html>

JS Minified(968字节):

function CSS3(e,t){function n(){if(l="","transition"==a)for(var e=0,t=i.length;t>e;e++)l+=i[e],t-1>e&&(l+=",");else l=i}var r=["","o","ms","moz","khtml","webkit"],i=t,o=!1,a=e,s=0,l="";this.init=function(){if(!o){o=!0;for(var e=0,t=r.length;t>e;e++)if(r[e]+=a,r[e]in element.style){s=e;break}n()}},this.changeStyle=function(e){if(!o)throw new CSS3Error;e.style[r[s]]=l},this.setValues=function(e){i=e,n()}}function Method(e){var t=e;this.delay=function(){var e;setInterval(function(){e?clearInterval(this):(e=t)()},2e3)}}var CSS3Error=function(){return{type:"Erro",message:"Classe não iniciada!"}},property1=new CSS3("border-radius","20px"),property2=new CSS3("transition",["all 3s"]),property3=new CSS3("sdads","dasds"),element=document.querySelector("#square");new Method(function(){try{property1.init(),property1.changeStyle(element),property2.init(),property2.changeStyle(element)}catch(e){alert(e instanceof CSS3Error?e.type+": "+e.message:e.message)}}).delay();

第二个例子:

var rules = "opacity: 0.5; transition: opacity 3s; -o-transition: opacity 3s; -ms-transition: opacity 3s; -moz-transition: opacity 3s; -webkit-transition: opacity 3s", selector = ".transition1", stylesheet = document.styleSheets[0];
("insertRule" in stylesheet) ? stylesheet.insertRule(selector + "{" + rules + "}", 0) : stylesheet.addRule(selector, rules, 0);
document.querySelector("#square").classList.toggle("transition1");

现场演示: https://jsfiddle.net/mv0L44zy/

答案 4 :(得分:1)

这个问题的目的现在已经过时了,但原理仍然适用。

在JavaScript中,您可以通过两种方式处理对象属性:

object.property
object['property']

后一种方法虽然不太方便,但允许使用无效的属性名称,也允许您使用变量。

元素样式是元素的style属性的属性,因此您也可以选择:

element.style.color
element.style['color']

对于使用点表示法无效的属性名称(例如包含连字符),您只能使用第二种表示法:

element.style['background-color']

为方便起见,这些麻烦的名称是使用camelCase复制的:

element.style.backgroundColor

为了完整起见,这也可以使用其他表示法:

element.style['backgroundColor']

在那里,您可以选择三个。

通常,任何属性,例如-ms-transition也可以使用:

element.style['-ms-transition']

不用担心如何表达点符号。

您不必再担心这些供应商前缀,但是原理仍然适用于其他尴尬的属性。

答案 5 :(得分:0)

function reg(){

var style = document.head.appendChild(document.createElement("style"));

style.innerHTML = "#main:after {border-right:400px solid #fde561; left:0 ; transition : 0.5s all ease}";

}