首先引入js运动框架
function getStyle(obj,name){
if(obj.currentStyle){
return obj.currentStyle[name];
} else{
return getComputedStyle(obj,false)[name];
}
} function startMove(obj, json, fnEnd) {
clearInterval(obj.timer);
obj.timer = setInterval(function() {
var bStop = true;
for (var attr in json) {
var cur = 0;
if (attr == "opacity") {
cur = Math.round(parseFloat(getStyle(obj, attr)) * 100);
} else {
cur = parseInt(getStyle(obj, attr))
}
var speed = (json[attr] - cur) / 10;
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
if (cur !== json[attr]) {
bStop = false;
};
if (attr == "opacity") {
obj.style.opacity = (speed + cur) / 100;
obj.style.filter = 'alpha(opacity:' + (speed + cur) + ')';
} else {
obj.style[attr] = cur + speed + 'px';
}
}
if (bStop) {
clearInterval(obj.timer);
if (fnEnd) fnEnd();
}
}, 30)
}
然后写轮播小案例
<!DOCTYPE html>
<html lang="en"> <head>
<meta charset="UTF-8">
<title>淘宝轮播</title>
<style>
ul,
li {
list-style: none;
margin: 0;
padding: 0;
} #wrap {
width: 400px;
height: 225px;
margin: 0 auto;
position: relative;
overflow: hidden;
} li {
float: left;
} #tips li {
margin: 5px;
border: 1px solid #f60;
width: 20px;
height: 20px;
line-height: 20px;
text-align: center;
color: white;
cursor: pointer;
} .active {
background: #f60;
} img {
vertical-align: top;
width: 400px;
} #content {
width: 2400px;
position: absolute;
left: -1200px;
} #content li {
float: left;
} #tips {
position: absolute;
right: 20px;
bottom: 5px;
}
</style>
</head> <body>
<div id="wrap">
<ul id="content">
<li><img src="img3/1.jpg" alt=""></li>
<li><img src="img3/2.jpg" alt=""></li>
<li><img src="img3/3.jpg" alt=""></li>
<li><img src="img3/4.jpg" alt=""></li>
<li><img src="img3/5.jpg" alt=""></li>
<li><img src="img3/6.jpg" alt=""></li>
</ul>
<ul id="tips">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
</div>
<script src="move.js"></script>
<script>
var wrap = document.getElementById('wrap');
var content = document.getElementById('content');
var tips = document.getElementById('tips');
var aLi = tips.getElementsByTagName('li');
var now = 0;
//var
for (var i = 0; i < aLi.length; i++) {
aLi[0].className = 'active'; //把初始状态定义好
content.style.left = 0 +'px';
aLi[i].index = i; //自定义属性
aLi[i].onclick = function() {
now = this.index;
play();
}
} function play() {
for (var j = 0; j < aLi.length; j++) {
aLi[j].className = '';
}
aLi[now].className = 'active'; //this.index = now; //反过来写就不对了大兄弟
//content.style.left = -400 * this.index + 'px';
startMove(content, {
left: -400 * now, //你还真别说,json格式就是这么写的
});
} function autoPlay() {
now++;
if (now == aLi.length) {
now = 0;
}
play();
} var timer = setInterval(autoPlay, 2000);
wrap.onmouseover = function(){ //这里如果把事件绑定到ul上的话,那么鼠标移入,下面对饮的li会不起作用,
clearInterval(timer); //因为li的层级比较高,所以应该把事件绑定到大的div上
}
wrap.onmouseout = function(){
timer = setInterval(autoPlay,2000);
//setInterval(autoPlay,2000); 不能这么写,凡是开的定时器,必须得赋值,要不然总会多开一个定时器,导致速度加快
}
</script>
</body> </html>
最终效果如下图,可实现鼠标翻页,鼠标悬停后停止轮播,