获取css属性计算值问题

都知道标准浏览器可以用 getComputedStyle 以及对应 ie 可以用 currentStyle 来取得元素渲染时的实际css属性值吧。

但是对于css缩写属性似乎很混乱,虽然标准 说缩写属性应该正确读取,


For some shorthand properties that take missing values from other sides, such as the margin, padding, and border-[width|style|color] properties, the minimum number of sides possible should be used; i.e., "0px 10px" will be returned instead of "0px 10px 0px 10px".

 

代码 :

 

但是现实是残酷的(在各个浏览器中打开)

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>

		<style type="text/css">
/*<![CDATA[*/

		.test {
		border:1px solid green;
		padding:10px
		}
		/*]]>*/
		</style>
		<title>
			test getComputedStyle
		</title>
	</head>
	<body>
		<div class="test" id="test">
			test
		</div><script type="text/javascript">
//<![CDATA[
		function getStyle(el,p){
		if(typeof el=='string') {
		el=document.getElementById(el);
		}
		if (window.getComputedStyle) {
		//document.defaultView
			var compStyle = window.getComputedStyle (el, "");
		}
		else {
			var compStyle = el.currentStyle;
		}
		return compStyle[p];

		}

		var el="test";

		alert("padding : "+getStyle(el,"padding"));
		alert("padding-top : "+getStyle(el,"paddingTop"));
		alert("border : "+getStyle(el,"border"));
		alert("border-width : "+getStyle(el,"borderWidth"));
		//]]>
		</script>
	</body>
</html>
 

 

竟然opera支持最好 ,关于shorthand 的不同看看这里 的总结:


Another difference is that the shorthand style properties are partially supported by the CSSStyleDeclaration and currentStyle objects. For example, the border is a shorthand style property, because the color, style and width of the border can be declared with it in one place.


The border property is supported in Opera, but not supported in Internet Explorer, Firefox and Safari.


The borderColor, borderStyle and borderWidth properties are supported in Internet Explorer and Opera, but not supported in Firefox and Safari.


The borderBottomColor, borderBottomStyle, borderBottomWidth, borderLeftColor, borderLeftStyle, borderLeftWidth, ... properties are supported in Internet Explorer, Firefox, Opera and Safari as well.


Therefore, if you need the current border settings, you must use the borderBottomColor, borderBottomStyle, borderBottomWidth, ... properties for a cross-browser solution.


单单 border 就很混乱。


可能解决:


若要达到完全兼容的话,把缩写手动拆开是个方法吧:


value("padding") = value(" padding-top")+" "+ value(" padding-right")

+" "+ value(" padding-bottom")

+" "+ value(" padding-left")


把子项值读出来然后拼起来可行,只不过有点麻烦,需要考虑所有的缩写形式。

 

 

 

PS: 复杂的 IE 取得css属性的绝对像素值问题

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值