currentStyle


用js的style屬性可以獲得html標簽的樣式,但是不能獲取非行間樣式。

解決方法:

在IE下可以用currentStyle;

在FF下用getComputedStyle;

然而,為了讓其兼容,解決方法,封裝成getStyle事件:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#div2{width:500px;height:100px;background-color:green;}
</style>
</head>
<body>
<div id="div2"></div>
</body>
</html>
<script>
最初:
if(oDiv2.currentStyle){
//IE
console.log(oDiv2.currentStyle.height);
}else{
// FF
console.log(getComputedStyle(oDiv2,false).width);
}

//封裝一個兼容性的獲取元素樣式的函數
//分析:哪個元素,哪個樣式
function getStyle(obj,attr){
if(obj.currentStyle){
      //IE
return obj.currentStyle[attr];
}else{
      //FF
return getComputedStyle(obj,false)[attr];
}
}
//用法
window.onload = function(){
var oDiv=document.getElementById("div2");
console.log(getStyle(oDiv,"width"));
}

//進一步封裝

//obj:獲取誰的樣式,attr:樣式名稱,value樣式的值
function css(obj,attr,value){
if(arguments.length==2){//獲取
return getStyle(obj,attr)
}else if(arguments.length == 3){//設置
obj.style[attr] =value;
}
}
//用法:
//      oBtn.onclick = function () {
// css(oDiv,"background","black");
// css(oDiv,"border","3px solid yellow");
// console.log(css(oDiv,"width"));
// }

</script>

補充:
JavaScript中,函數本身的length屬性和arguments.length到底有什么區別?
1,函數本身有length屬性,表示參數的個數。
arguments.length也表示參數的個數。

2,函數對象的length屬性是形式參數的個數;
arguments偽變量的length屬性是某次調用的實際參數的個數。
  例如:
    function func(a,b,c){
      console.log(arguments.length);//輸出:3
    }
      console.log(func.length)//輸出: 1
    func(1);
以上是后來發現錯的,2017-03-16更正了以后:
      function func(a,b,c){
       console.log("arguments:"+arguments.length); //輸出 arguments::1
    }
    console.log("length:"+func.length); //輸出 length: 3
    func(1);





3,
函數本身也是對象,對象就有屬性,函數有length屬性,比如: function fn(x,y,z) {}中 fn.length=3,說明了函數的形參個數; 而在函數體內,arguments.length表示傳入函數的實參個數,比如:function fun(1,2) { console.log(arguments.length)} 中實參的個數為arguments.length=2

4,fn.length: 形參個數
arguments.length: 實參個數

//拓展:

//arguments  數組(所有的參數)  可變參(不定參)
function sum2() {
var result = 0;
var i = 0;
for(i=0;i<arguments.length;i++){
result += arguments[i];
}
console.log(result);//輸出13

}
sum2(4,4,5);

 總結,除了可以用arguments去判斷參數個數,還可以做不定參的運算。
    



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM