近排看了下JS,順便也看了下CSS,然后突然想試一下JS控制CSS,畢竟將來可能會用到,上網(wǎng)查了下得到如下信息:
一賦值方式 : 用法:元素(節(jié)點).style.css屬性
只不過css屬性寫法特殊點
一個單詞的就直接寫,中間用橫杠的前一個開頭字母小寫,后一個開頭字母大寫,不用橫杠鏈接
還有幾個特殊,比如常見的css的float屬性要寫成
document.getElementById("div01").style.cssFloat;
因為float是js保留字。
其他的沒是區(qū)別了
document.getElementById("div01").style.height;
document.getElementById("div01").style.lineHeight;
document.getElementById("div01").style.backgroundColor;
下面寫了個深入一點的例子,自定義一個對象里面存放所需的CSS屬性,然后利用這些屬性設置當前節(jié)點樣式:
function changeCss(){
var s={backgroundColor:"#0099FF",width:"40px"};//包含了CSS屬性
var node=document.getElementById("a");獲取節(jié)點
for(var c in s){
eval("node.style."+c+"=s[c]");//原本執(zhí)行是這樣的:node.style.proName=s[c];但由于proName(屬性名)是未知的需要遍歷s對象獲取,所以需要使用eval函數(shù),通過這個函數(shù),存入的字符串可以當表達式執(zhí)行,這是個很實用的方法哦!
}
}
二、利用節(jié)點的className屬性改變其CSS
再有一種方式就是通過控制標簽的class屬性,用于更改整個CSS樣式,用法:
<font id="a">aa</font>
/////////////////////////////////////////////////
<style id="css" type="text/css">
.css{
background:red;
}
</style>
////////////////////////////////////////////////////
var node=document.getElementById("a");
node.className="css";
三、獲取節(jié)點相關的CSS屬性值
以上方式可以說都是向CSS設置值或更改CSS,如何獲取當前節(jié)點的CSS樣式屬性值呢?查了很久終于查到:
IE下:node.currentStyle['屬性名']
hh下:document.defaultView.getComputedStyle (node,null)['屬性名'];
網(wǎng)上一個比較方法是:
function GetCurrentStyle (obj, prop) {
if(obj.currentStyle){
return obj.currentStyle[prop];
}
else if (window.getComputedStyle) {
propprop = prop.replace (/([A-Z])/g, "-$1");
propprop = prop.toLowerCase ();
return document.defaultView.getComputedStyle (obj,null)[prop];
}
}