Grammar:
nodeObject.style.cssProperty
Among them, nodeObject is the node object and cssProperty is the CSS property.
For example:
document.getElementById("demo").style.height; document.getElementById("demo").style.border;
Note: For CSS properties separated by "-", remove the "-" and capitalize the first letter after the "-". For example:
background-color should be written as backgroundColor
line-height should be written as lineHeight
For example:
document.getElementById("demo").style. backgroundColor; document.getElementById("demo").style.lineHeight;
For example, get the style of the node with id="demo" :
<div id="demo" style="height:50px; width:250px; margin-top:10px; text-align:center; line-height:50px; background-color:#ccc;"> 点击这里获取CSS样式 </div> <script type="text/javascript"> document.getElementById("demo").onclick=function(){ alert( "高度:"+this.style.height+"\n"+ "宽度:"+this.style.width+"\n"+ "上边距:"+this.style.marginTop+"\n"+ "对齐:"+this.style.textAlign+"\n"+ "行高:"+this.style.lineHeight+"\n"+ "背景颜色:"+this.style.backgroundColor ); } </script>
Slightly modify the above code to separate the CSS style from the HTML:
<style> #demo{ height:50px; width:250px; margin-top:10px; text-align:center; line-height:50px; background-color:#ccc; } </style> <div id="demo"> 点击这里获取CSS样式 </div> <script type="text/javascript"> document.getElementById("demo").onclick=function(){ alert( "高度:"+this.style.height+"\n"+ "宽度:"+this.style.width+"\n"+ "上边距:"+this.style.marginTop+"\n"+ "对齐:"+this.style.textAlign+"\n"+ "行高:"+this.style.lineHeight+"\n"+ "背景颜色:"+this.style.backgroundColor ); } </script>
It can be found that the CSS style cannot be obtained after separating the CSS style from the HTML code. This is because
nodeObject.style.cssProperty
obtains the style defined by the style attribute on the DOM node. If the style attribute does not exist, or the style attribute does not define the corresponding style, it cannot Obtained.
In other words, JavaScript will not go to the <style> tag or CSS file to get the corresponding style, but can only get the style defined by the style attribute.