title: 写了个图片上下滑的东西 date: 2015-08-18 12:41:44 tags: 滑动 category: javascript
平常不怎么写动画,怕面试问到,刚好看到这个题目,就写写试试。代码写的有点乱...
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>滑动</title>
</head>
<style>
* {
margin: 0;
padding: 0;
}
li {
list-style: none;
}
img {
border: none;
display: block;
}
.content {
margin: 150px auto auto auto;
width: 470px;
height: 150px;
position: relative;
overflow: hidden;
}
ol {
position: absolute;
bottom: 20px;
right: 20px;
z-index: 2;
}
ol li {
float: left;
margin-right: 5px;
background-color: #fff;
width: 15px;
height: 15px;
text-align: center;
cursor: pointer;
}
ol li.active {
background-color: #f47500;
}
.content ul {
position: absolute;
}
</style>
<body>
<div class="content">
<ol id="ol">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ol>
<ul id="ul">
<li><a href="javascript:;"><img src="http://www.codefans.net//jscss/demoimg/201108/1.jpg" alt="广告一"/></a></li>
<li><a href="javascript:;"><img src="http://www.codefans.net//jscss/demoimg/201108/2.jpg" alt="广告二"/></a></li>
<li><a href="javascript:;"><img src="http://www.codefans.net//jscss/demoimg/201108/3.jpg" alt="广告三"/></a></li>
<li><a href="javascript:;"><img src="http://www.codefans.net//jscss/demoimg/201108/4.jpg" alt="广告四"/></a></li>
<li><a href="javascript:;"><img src="http://www.codefans.net//jscss/demoimg/201108/5.jpg" alt="广告五"/></a></li>
</ul>
</div>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.js"></script>
<script>
var len = $('#ul li').length;
$('#ol li').eq(0).addClass('active').siblings().removeClass('active');
var i = dis = 0;
var ulTop = $('#ul').offset().top - 150;
var slide = function (dz) {
if (dz == 'down')i++, h = -150;
else i--, h = 150;
$('#ol li').eq(i).addClass('active').siblings().removeClass('active');
var ulTop = $('#ul').offset().top - 150;
$('#ul').animate({'top': ulTop + h + 'px'}, 500);
}
var slide2 = function (n) {
$('#ol li').eq(n).addClass('active').siblings().removeClass('active');
$('#ul').animate({'top': -n * 150 + 'px'}, 500);
}
var autoshow = setInterval(function () {
if (i >= len - 1) {
dis = 1;
} else if (i <= 0) {
dis = 0;
}
if (dis == 0) {
slide('down');
}
if (dis == 1) {
slide('up');
}
}, 2000);
$('#ol li').mouseover(function () {
clearInterval(autoshow);
})
$('#ol li').mouseout(function () {
autoshow = setInterval(function () {
if (i >= len - 1) {
dis = 1;
} else if (i <= 0) {
dis = 0;
}
if (dis == 0) {
slide('down');
}
if (dis == 1) {
slide('up');
}
}, 2000);
})
$('#ol li').on('click', function () {
var index = $(this).index();
i = index;
slide2(index);
})
</script>
</body>
</html>