<分区>
标签 javascript jquery html css
我已经创建了自己的 slider ,现在我在使用子弹导航后再次调用自动滑动设置间隔函数时遇到问题。 “设置超时(自动滑动,1000);”不管用。我试过的代码如下。请给我一个解决方案。谢谢。
<!doctype html>
<head>
<title> Custom Slider </title>
<style type="text/css">
body
{
margin: 0;
padding: 0;
}
.slide
{
float: left;
width: 960px;
height: 300px;
background-color: #000;
}
.slide h1
{
color: #fff;
}
#container
{
width: 960px;
overflow: hidden;
margin: auto;
margin-top: 100px;
}
#wrapper
{
position: relative;
right: 0px;
}
#bullets li
{
cursor: pointer;
}
</style>
</head>
<body>
<div id="container">
<div id="wrapper">
<div class="slide">
<h1>Slide 1</h1>
</div>
<div class="slide">
<h1>Slide 2</h1>
</div>
<div class="slide">
<h1>Slide 3</h1>
</div>
<div class="slide">
<h1>Slide 4</h1>
</div>
<div style="clear: both;"> </div>
</div>
</div>
<ol id="bullets">
</ol>
<script src="https://code.jquery.com/jquery-2.2.3.min.js" integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo=" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function(){
var slideWidth = $('.slide').width();
var slideLength = $('.slide').length;
var totalWidth = slideWidth * slideLength;
$('#wrapper').css('width', totalWidth);
var currentPos = $('#wrapper').position().right;
var currentIndex = 0;
var autoSlide;
function auto(){
currentIndex += 1;
if(currentIndex > slideLength - 1)
{
currentIndex = 0;
}
$('#wrapper').animate({right: currentIndex * slideWidth});
}
var autoSlide = setInterval(auto, 1000);
$('.slide').each(function(){
$('#bullets').append('<li class="bullet"> </li>');
});
$('.bullet').click(function(){
clearInterval(autoSlide);
var bulletIndex = $(this).index();
if(bulletIndex > slideLength - 1)
{
bulletIndex = 0;
}
$('#wrapper').animate({right: bulletIndex * slideWidth});
currentIndex = bulletIndex;
setTimeout(autoSlide, 1000);
});
});
</script>
</body>
最佳答案
setTimeout(autoSlide, 1000);
正在将旧计时器句柄传递到 setInterval
,这将不起作用。再次传递函数:
autoSlide = setTimeout(auto, 1000);
另请注意,setTimeout
将设置一个只触发 一次 的计时器,而您原来的 setInterval
将设置一个重复 计时器,因此您可能希望在那里设置 setInterval
。
关于javascript - 单击元素符号导航后设置间隔不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37117536/
相关文章:
javascript - 在窗口上添加点击事件,但忽略所有以 https 开头的链接
jquery - 如果选中复选框,则需要输入 ="text"字段
jquery - Android 手机浏览器 jQuery keydown 问题
javascript - HTML5/Javascript 以一定 Angular 在屏幕上移动对象
javascript - 从文本字段 javascript 表中获取值
javascript - 如果我的对象中有一个数组并且该对象位于一个大数组中,我该如何更新 React Native 状态?