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

 

先贴个链接:

 

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来获得属性的例子更有学习意义:

 

代码如下:

 

 

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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值