jquery实现按键浮动
时间: 2024-03-05 12:44:45 浏览: 65
jQuery浮动菜单实现
以下是使用jQuery实现按键浮动的示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>按键浮动示例</title>
<style type="text/css">
.container {
position: relative;
width: 500px;
height: 300px;
margin: 0 auto;
overflow: hidden;
}
.slider {
position: absolute;
top: 0;
left: 0;
width: 2000px;
height: 300px;
}
.slider img {
float: left;
width: 500px;
height: 300px;
}
.btn {
position: absolute;
top: 50%;
margin-top: -20px;
width: 40px;
height: 40px;
background-color: rgba(0, 0, 0, 0.5);
color: #fff;
text-align: center;
line-height: 40px;
font-size: 20px;
cursor: pointer;
z-index: 999;
}
.btn-prev {
left: 0;
}
.btn-next {
right: 0;
}
</style>
</head>
<body>
<div class="container">
<div class="slider">
<img src="img/1.jpg" alt="">
<img src="img/2.jpg" alt="">
<img src="img/3.jpg" alt="">
<img src="img/4.jpg" alt="">
<img src="img/5.jpg" alt="">
</div>
<div class="btn btn-prev"><</div>
<div class="btn btn-next">></div>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var slider = $('.slider');
var sliderWidth = slider.width();
var sliderImg = slider.find('img');
var sliderImgLen = sliderImg.length;
var sliderTotalWidth = sliderWidth * sliderImgLen;
var currentIndex = 0;
var timer = null;
slider.css('width', sliderTotalWidth);
$('.btn-prev').click(function() {
currentIndex--;
if (currentIndex < 0) {
currentIndex = sliderImgLen - 1;
slider.css('left', -sliderWidth * (sliderImgLen - 1));
}
slider.stop().animate({
left: -sliderWidth * currentIndex
}, 500);
});
$('.btn-next').click(function() {
currentIndex++;
if (currentIndex > sliderImgLen - 1) {
currentIndex = 0;
slider.css('left', 0);
}
slider.stop().animate({
left: -sliderWidth * currentIndex
}, 500);
});
function autoPlay() {
timer = setInterval(function() {
$('.btn-next').trigger('click');
}, 2000);
}
autoPlay();
$('.container').hover(function() {
clearInterval(timer);
}, function() {
autoPlay();
});
});
</script>
</body>
</html>
```
阅读全文