通过for循环和背景定位制作图片的显示效果

时间:2020-12-21 14:30:52

html部分:

<div id="wrap">
</div>

css部分:

#wrap{
position: absolute;
top: 0;
left: 0;}
#wrap div{width: 50px;
height: 50px;
display: inline-block;
position:absolute;
transition: 0.5s;
opacity: 0.2;}

JavaScript部分:

window.onload = function () {
var oWrap = document.getElementById('wrap');
var aDiv = oWrap.getElementsByTagName('div');
var str = '';

//通过背景定位将图片拼接在一起
for (var i=0;i<280;i++){
str += '<div style="top:' + Math.floor(i/20)*52 + 'px;left:' + i%20*52 + 'px;background-image: url(img/红色裙子裁剪.jpg);background-position:' + (-i%20*52) + 'px ' + (-Math.floor(i/20)*52) + 'px;"></div>';
}
oWrap.innerHTML = str;

//添加鼠标移入和移开动画
for (var i=0;i<aDiv.length;i++){
aDiv[i].onmouseover = function () {
this.style.opacity = 1;
this.style.transform = 'scale(1.6)';
}
aDiv[i].onmouseout = function () {
this.style.transform = 'scale(1)';
}
}
}