获取样式的时候用offsetWidth 这类有Bug 要用 obj.currentStyle.width 或getComputedStyle(obj,null).width

<style type="text/css">
			div{
				width: 100px;
				height: 100px;
				background: red;
				float: left;
				margin: 20px;
			}
		</style>
	</head>
	<body>
		<div id="box1"></div>
		<div id="box2">哈哈</div>
	</body>
		<script type="text/javascript">
			window.onload = function(){
				var oBox1 = document.getElementById('box1');
				var oBox2 = document.getElementById('box2');
				
				oBox1.onmouseover = function(){
					changes(this,'height',200);
				}
				oBox1.onmouseout = function(){
					changes(this,'height',100);
				}
				
				oBox2.onmouseover = function(){
					changes(this,'width',200);
				}
				oBox2.onmouseout = function(){
					changes(this,'width',100);
				}
				/*封装一个函数 获取内联样式的属性 (不能同offsetWidth 这类offset方法 有Bug的)*/
				function getStyle(obj,name){
					//判断IE系统中时候存在currentStyle这个方法
					if(obj.currentStyle){
						return obj.currentStyle[name];
					}else{
						//不存在 即是非IE浏览器 就用以下方法获取 
						//不封装函数的写法 :getComputedStyle(oDiv,null).width;
						//name是属性 调用函数时候 写法  getStyle(oDiv,'width'); 是字符串类型
						return getComputedStyle(obj,null)[name];
					}				
				}
				var timer = null;
				function changes(obj,name,target){
					clearInterval(obj.timer);
					//obj.timer 是给每个div都添加上这个timer定时器
					obj.timer = setInterval(function(){
						//目标值 减去 变化值 赋值 到 speed 
						//因为 getStyle函数获取到的样式是字符串 比如width是'100px'
						//所以 需要用parseInt() 这个方法 强制将字符串转化为数字number类型
						var speed = (target - parseInt(getStyle(obj,name))) / 10;
						speed = speed>0?Math.ceil(speed):Math.floor(speed);
						obj.style[name] = parseInt(getStyle(obj,name)) + speed + 'px';
					},30);
				}
							
			}
		</script>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值