分享一个由原生JS实现的图片切换特效,效果如下:
原理比较简单,实现的代码如下:
代码语言:javascript复制<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>原生JS实现切换不同图片的特效</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
#div1 {
width: 200px;
height: 200px;
position: absolute;
left: 50%;
margin-left: -100px;
top: 0;
}
</style>
</head>
<body>
<div id='div1'></div>
<script type="text/javascript">
for (var i = 0; i < 10; i ) {
for (var j = 0; j < 10; j ) {
var oDiv = document.createElement('div');
oDiv.style.background = 'url(images/0.jpg)';
oDiv.style.backgroundPosition = -j * 20 'px ' (-i * 20) 'px';
oDiv.style.width = div1.offsetWidth / 10 'px';
oDiv.style.height = div1.offsetHeight / 10 'px';
oDiv.style.transition = (0.3 Math.random() * 1) 's';
oDiv.style.float = 'left';
div1.appendChild(oDiv);
}
};
var allDiv = div1.children;
var index = allDiv.length - 1;
var t = null
div1.onclick = function () {
t = setInterval(function () {
if (index == -1) {
clearInterval(t);
return;
}
allDiv[index].style.backgroundImage = 'url(images/1.jpg)';
allDiv[index].style.transform = 'translateY(200px)';
index--;
}, 30);
}
</script>
</body>
</html>