【前端学习】JavaScript闭包 获取html元素计算后的样式

·函数外部环境闭包影响

i的定义在function外部,所以受闭包影响,需利用this关键字,触发事件的该对象。j的定义在function内部,所以不受闭包影响。

for(var i = 0 ; i < pa1.length ; i ++) {
			// 提前将i保存在index属性中
			pa1[i].index = i;
			// 点击事件
			pa1[i].onclick = function() {
				for(var j = 0 ;j < pa2.length; j ++) {
					pa2[j].style.backgroundColor = "blue";
				}
				pa2[this.index].style.backgroundColor = "red";
			};
		}

·不同版本浏览器获取html元素计算后的样式

	<div class="box" id="box" style="width: 100px;">1</div>
	<script type="text/javascript">
		var oBox = document.getElementById("box");
		console.log(oBox.style.width);
	</script>

通过style只能读取行内样式不能读取CSS计算后的样式。

  • 高级浏览器通过getComputedStyle(),getPropertyValue() 获取计算后样式

    单一属性:短横 border-width

window.getComputedStyle(oBox).getPropertyValue("width");
window.getComputedStyle(oBox)["border-width"];
  • IE6,7,8通过currentStyle 获取计算后样式

    单一属性:驼峰 borderWidth

oBox.innerHTML = oBox.currentStyle.width;
oBox.innerHTML = oPic.currentStyle["borderColor"];
  • 兼容

    利用函数自动识别高级浏览器或低级浏览器,并将用户输入想要获得属性自动转化为短横或驼峰形式。

	<script type="text/javascript">
		// 获取元素对象
		var oBox = document.getElementById("box");
		var oPic = document.getElementById("pic");
		// 将img边框宽度输出
		// oBox.innerHTML = getValue("borderWidth",oPic);
		oBox.innerHTML = getValue("border-width",oPic);

		// 参数   border-width,borderWidth
		// 返回值
		function getValue(property, obj) {
			if(window.getComputedStyle) {
				// 高级
				// 将属性名改为短横写法borderWidth改为border-width
				property = property.replace(/([A-Z])/g,function(match,$1) {
					return "-" + $1.toLowerCase();
				});
				// 将属性值返回
				return window.getComputedStyle(obj)[property];
			}else {
				// IE border-width改为borderWidth
				property = property.replace(/-([a-z])/g,function(match,$1) {
					return $1.toUpperCase();
				});
				// 将属性值返回
				return obj.currentStyle[property];
			}
		}		
	</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值