商务合作:179001057@qq.com

如何获得某个元素的css属性。

技术2022-05-12  0


某平台价值19860元的编程课程资料免费领取【点我领取】


 

先贴个链接:

 

http://www.quirksmode.org/dom/getstyles.html

 

原文第一句话说的就是我的疑惑。。。

 

“Sometimes you'll want to see what styles the default document view has. For instance, you gave a paragraph an width

 

of 50%, but how do you see how many pixels that is in your users' browser?”

 

看完上面一大部分讲offsetHeight等等之类的,收获颇多;

 

不过觉得下面的用javascript来获得属性的例子更有学习意义:

 

代码如下:

 

function getStyle(el, styleProp){ var x =document.getElementById(el); var y; if(x.currentStyle){ y = x.currentStyle[styleProp]; }else if(window.getComputedStyle){ y=document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp); } return y; }

 

First we pass the function the id of the HTML element and the style property we wish to access

function getStyle(el,styleProp) {

Then we store the HTML element in x:   //从这里可以看出选择的方式是通过传递id参数,用x保存html元素

var x = document.getElementById(el);

 

First the Explorer way: the currentStyle of the HTML element: //首先的方法适合ie浏览器使用

if (x.currentStyle) var y = x.currentStyle[styleProp];

 

Then the Mozilla way: the getComputedStyle() method, which also works in Opera: //接下来是Firefox和Opera的方法

else if (window.getComputedStyle) var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);

 

Finally return y to whichever function asked for it (in this page it's the function prepare() that is called when you submit the form or click the link 'get the style').                //将y的值返回,y中存的就是你想要的style的属性                               

return y; }

Although this function doesn't yet work well, it's the best you can do.


最新回复(0)