点击图片图片上下抖动

HTML

<img src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1511501753&di=af2dc05f9decb517801a91b49a26bd18&imgtype=jpg&er=1&src=http%3A%2F%2Fww1.sinaimg.cn%2Fthumb300%2F9651d910gw1f8f9266axhj20p00e2jtd.jpg"/>
<img src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1511501753&di=af2dc05f9decb517801a91b49a26bd18&imgtype=jpg&er=1&src=http%3A%2F%2Fww1.sinaimg.cn%2Fthumb300%2F9651d910gw1f8f9266axhj20p00e2jtd.jpg"/>
<img src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1511501753&di=af2dc05f9decb517801a91b49a26bd18&imgtype=jpg&er=1&src=http%3A%2F%2Fww1.sinaimg.cn%2Fthumb300%2F9651d910gw1f8f9266axhj20p00e2jtd.jpg"/>
<img src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1511501753&di=af2dc05f9decb517801a91b49a26bd18&imgtype=jpg&er=1&src=http%3A%2F%2Fww1.sinaimg.cn%2Fthumb300%2F9651d910gw1f8f9266axhj20p00e2jtd.jpg"/>

CSS

*{
	margin: 0;
	padding: 0;
}
img{
	width: 100px;
	height: 100px;
	position: absolute;
	left: 10px;
	top: 100px;
}
img:nth-of-type(2){
	left: 150px;
}
img:nth-of-type(3){
	left: 300px;
}
img:nth-of-type(4){
	left: 450px;
}

JS

var aImg=document.getElementsByTagName("img");
for (var i=0;i<aImg.length;i++) {
	shake(aImg[i],"top");
}

//函数封装
function shake(obj,attr){
	//生成数组[20,-20,18,-18,16,-16,14,-14,12,-12,10,-10,8,-8,6,-6,4,-4,2,-2,0,-0]
	var arr=[];
	for (var i=22;i>1;i--) {
		arr.push(i-2,-(i-2));
	}
	obj.num=0;
	var num=parseInt(getStyle(obj,attr));
	obj.onclick=function(){
		clearInterval(obj.timer);
		obj.timer=setInterval(function(){
			var attr1=num+arr[obj.num];
			if(obj.num>arr.length-1){
				clearInterval(obj.timer);
				obj.num=0;
			}
			obj.style[attr]=attr1+"px";
			obj.num++;
		},30)
	}
}

function getStyle(obj,attr){
	if(obj.currentStyle){
		return obj.currentStyle[attr];
	}else{
		return getComputedStyle(obj)[attr];
	}
}

  

posted @ 2017-11-17 16:21  carol72  阅读(271)  评论(0编辑  收藏  举报