简体   繁体   English

我在CSSStyleDeclaration原型中添加了一个变量,但无法对其进行修改

[英]I've added a variable to CSSStyleDeclaration prototype, but can't modify it

I don't really understand prototypes, so it might be my fault, but theorically if I add a variable to a prototype, I will be able to change it in its instances, right? 我不太了解原型,所以这可能是我的错,但是从理论上讲,如果我向原型添加变量,则可以在其实例中进行更改,对吗?

Here the code: 这里的代码:

    <head>
        <script>
            CSSStyleDeclaration.prototype["foo"] = "something";
        </script>
    </head>
    <body>
        <div style="foo:'maybe'" id ="myId"></div>
        <script>
            var el = document.getElementById("myId");
            console.log(el.style.foo);
        </script>
    </body>

The console returns "something", why? 控制台返回“某物”,为什么?

That's because foo is not a standard property, so 那是因为foo不是标准属性,所以

However, on browsers that support CSS variables , you could use them: 但是,在支持CSS变量的浏览器上,可以使用它们:

 function getFoo(el) { return getComputedStyle(el).getPropertyValue('--foo'); } snippet.log("body: " + getFoo(document.body)); snippet.log("#myId: " + getFoo(document.getElementById('myId'))); 
 * { --foo: 'something'; } 
 <div style="--foo: 'maybe'" id="myId"></div> <!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --><script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM