CSS代码是否初始化DOM对象的.style属性? [英] Does CSS code initialize .style properties of DOM objects?

查看:88
本文介绍了CSS代码是否初始化DOM对象的.style属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个简单的DOM事件示例:请参阅< p>点击我!< / p>
< / div>

< script>
function toggleFloat(ele){
var current = ele.style.cssFloat;
console.log(cssFloat:+ current);
if(current ===left)
ele.style.cssFloat =right;
else
ele.style.cssFloat =left;
}
< / script>

伴随css:

  #squirrel {
float:left;
}

注意到奇怪行为:在DOM中,#松鼠的初始值为cssFloat属性是。 (打开开发人员控制台查看,或者注意#squirrel在第二个事件触发之前不会移动)。



我的问题是: CSS代码是否应该初始化DOM对象的cssFloat属性? ...或任何风格属性?

解决方案

样式属性表示其内联样式(使用样式属性定义)。



这些不会被您的css文件中定义的css规则修改。浏览器根据这些规则和内联样式计算最终样式。

最终计算的样式可以使用 MDN:Window.getComputedStyle()



您通常应该避免使用内联样式属性。通常你应该尝试使用 class 来操纵某个元素的外观。另外,只有在确实没有方法时才能使用样式属性动态更改内联样式,例如,如果你需要动态地移动一个元素。您还可以阅读内联标签与内联CSS属性的答案以获取更多信息。


Background:

I created a simple DOM event example: see jsfiddle here.

<div id="squirrel" onmouseover="toggleFloat(this)">
    <p>Click me!</p>
</div>

<script>
    function toggleFloat(ele){
        var current = ele.style.cssFloat;
        console.log("cssFloat: "+current);
        if(current==="left")
            ele.style.cssFloat="right";
        else
            ele.style.cssFloat="left";
    }
</script>

Accompanying css:

#squirrel{
  float:left;
}

Odd behaviour was noticed: In the DOM, the #squirrel's initial value for the cssFloat property was "". (Open the developer console to see this. Or notice that the #squirrel doesn't move until the second event fires.).

My question is: Should the CSS code not have initialized the cssFloat property of the DOM object? ...or any of the style properties for that matter?

解决方案

The style property of an element represents its inline style (defined with the style attribute).

Those are not modified by the css rules defined in a your css file. The browser computes the final style based on those rules and the inline style.

The final computed style can be retrieved using MDN: Window.getComputedStyle()

You generally should avoid to use inline style attributes. Normally you should try to use class to manipulate the appearance of a certain element. Also the use of the style property to dynamically change the inline style should only be used if there is really no way around it, e.g. if you need to move an element dynamically. You could also read the answer to Inline tags vs. inline css properties for more informations.

这篇关于CSS代码是否初始化DOM对象的.style属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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