Javascript 如何使用javascript设置CSS3过渡?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8742249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:17:48  来源:igfitidea点击:

How to set CSS3 transition using javascript?

javascriptcss

提问by Hakan

How can I set CSS using javascript (I don't have access to the CSS file)?

如何使用 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;
}

For example:

例如:

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

采纳答案by bardiir

You should look here: http://www.javascriptkit.com/javatutors/setcss3properties.shtml

你应该看这里:http: //www.javascriptkit.com/javatutors/setcss3properties.shtml

As you can see setting CSS Properties with "-" just results in the next character to be capital:

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

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

回答by gion_13

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

function toCamelCase(str) {
    return str.toLowerCase().replace(/(\-[a-z])/g, function() {
        return .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;
        }
    });
}

usage :

用法 :

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

Here's a live demo.

这是一个现场演示

回答by Fabrizio Calderan

you should use the camelCase notation like so:

你应该像这样使用驼峰命名法:

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

like every property composed by more than one word and hyphen-separated (e.g. css background-positionturns into js backgroundPosition.

就像由多个单词组成并以连字符分隔的每个属性(例如 cssbackground-position变成 js backgroundPosition

Probably at this time not every browser adopted this notation in properties involving browser specific prefixes, so there are some browser like firefox still accepting Mozinstead of moz(see https://bugzilla.mozilla.org/show_bug.cgi?id=607381)

可能此时并非每个浏览器都在涉及浏览器特定前缀的属性中采用此表示法,因此有一些像 firefox 这样的浏览器仍然接受Moz而不是moz(参见https://bugzilla.mozilla.org/show_bug.cgi?id=607381

回答by Enoque Carvalho

First example:

第一个例子:

<!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 bytes):

JS 缩小版(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();

Second example:

第二个例子:

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");

Live demo:https://jsfiddle.net/mv0L44zy/

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

回答by Mohamed Mostafa Goda

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}";

}

回答by Manngo

The purpose of this question is obsolete now, but the principle is still relevant.

这个问题的目的现在已经过时了,但原则仍然相关。

In JavaScript, you have two ways of addressing object properties:

在 JavaScript 中,您有两种寻址对象属性的方法:

object.property
object['property']

The latter method, though it is less convenient, allows for property names which would be invalid, and also allows you to use a variable.

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

Element styles are properties of the element's style property, so you also have a choice:

元素样式是元素的样式属性的属性,因此您还有一个选择:

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

For property names which are invalid using the dot notation, such as containing a hyphen, you can only use the second notation:

对于使用点符号无效的属性名称,例如包含连字符,您只能使用第二个符号:

element.style['background-color']

For your convenience these troublesome names are replicated using camelCase:

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

element.style.backgroundColor

And, for completeness, this can also use the alternative notation:

而且,为了完整性,这也可以使用替代符号:

element.style['backgroundColor']

There, you have a choice of three.

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

Generally, any property, such as -ms-transitioncan also be accessed using:

通常,任何属性,例如-ms-transition也可以使用以下方法访问:

element.style['-ms-transition']

without worrying about how to express the dot notation.

无需担心如何表达点符号。

Not that you need to worry about these vendor prefixes any more, but the principal still applies to other awkward properties.

并不是说您不再需要担心这些供应商前缀,但该原则仍然适用于其他笨拙的属性。