JS獲取元素任意屬性值
阿新 • • 發佈:2018-11-19
相容程式碼:
//獲取元素的任意屬性值
//ele是要獲取的元素,attr為要獲取的屬性
function getStyle(ele,attr){
return window.getComputedStyle?window.getComputedStyle(ele,null)[attr]:getCurrentStyle[attr];
}
利用這個js的案例:
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> * { margin: 0; padding: 0; } #dv { width: 200px; height: 100px; background-color: green; position: absolute; top: 20px; } </style> </head> <body> <input type="button" value="變寬400px" id="btn1" /> <input type="button" value="向下移動800px" id="btn2" /> <div id="dv"></div> <script src="js/common.js"></script> <script src="js/getStyle.js"></script> <script> my$('btn1').onclick=function(){ move(my$('dv'),'width',400,10); }; my$('btn2').onclick=function(){ console.log(getStyle(this,'height')); console.log(getStyle(my$('dv'),'top')); move(my$('dv'),'top',800,10); }; function move(ele,attr,aim,step){ //每次點選執行函式的時候都清除定時器,防止連續點選加快移動速度 //之所以用ele.time是為了不出time undefined的錯誤 clearInterval(ele.time); ele.time=setInterval(function() { //獲取當前屬性值,是帶單位的,parseInt()獲得純數字 var now =parseInt(getStyle(ele,attr)); //確定每次移動的單位距離step的正負,如果目標距離aim大於當前距離,step為正,反之step為負 //每次執行函式之前將step初始化為正值 step = Math.abs(step); step = now < aim ? step : -step; //設定每次執行函式當前得位置都在變化,變化量為step now += step; //設定元素的位置,如果正在向目標位置移動,那麼Math.abs(now-aim)>Math.abs(step),如果已經在目標位置的地方 //但是不能精確則Math.abs(now-aim)<Math.abs(step),這兩種情況的當前位置是不一樣的 if (Math.abs(now - aim) > Math.abs(step)) { ele.style[attr] = now+'px'; } else if (Math.abs(now - aim) < Math.abs(step)) { clearInterval(time); ele.style[attr] = aim+'px'; } else if(Math.abs(now - aim) === Math.abs(step)){ ele.style[attr] = aim+'px'; } },20); } </script> </body> </html>
通過傳入不同的attr,對div進行不同的改變。