我目前正在尝试为网站构建图片滑块。我已经编写了所需的所有代码,但是我在使用jQuery响应或在HTML文档中工作时遇到了麻烦。
页面的HTML是:
var currentIndex = 0,
items = $('.container div'),
itemsAmt = items.length;
function cycleItems() {
var item = $('.container div').eq(currentIndex);
items.hide();
item.css('display', 'inline-block');
}
var autoSlide = setInterval(function() {
currentIndex += 1;
if (currentIndex > itemsAmt - 1) {
currentIndex = 0;
}
cycleItems();
}, 3000);
$('.next').click(function() {
clearInterval(autoSlide);
currentIndex += 1;
if (currentIndex > itemsAmt - 1) {
currentIndex = 0;
}
cycleItems();
});
$('.prev').click(function() {
clearInterval(autoSlide);
currentIndex -= 1;
if (currentIndex < 0) {
currentIndex = itemsAmt - 1;
}
cycleItems();
});
.container {
max-width: 400px;
background-color: black;
margin: 0 auto;
text-align: center;
position: relative;
}
.container div {
background-color: white;
width: 100%;
display: inline-block;
display: none;
}
.container img {
width: 100%;
height: auto;
}
button {
position: absolute;
}
.next {
right: 5px;
}
.prev {
left: 5px;
}
<html>
<head>
<link rel="stylesheet" type="text/css" href="./css/sliderstyle.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="./js/sliderjs.js"></script>
</head>
<body>
<section class="demo">
<button class="next">Next</button>
<button class="prev">Previous</button>
<div class="container">
<div style="display: inline-block;">
<img src="./img/1.jpg">
</div>
<div>
<img src="./img/2.jpg">
</div>
<div>
<img src="./img/3.jpg">
</div>
</div>
</section>
</body>
</html>
答案 0 :(得分:0)
使用文档准备
// A $( document ).ready() block.
$( document ).ready(function() {
console.log( "ready!" );
});
答案 1 :(得分:0)
您可以考虑两件事: 要么等待DOM树的就绪状态,这会导致所有DOM元素和引用都正确生成:
$(document).ready(function() {
//your code here
});
这将是更安全的方式。另一种可能的解决方案是将JavaScript文件包含在代码的底部,例如在</body>
HTML-Tag之前。此外,等待DOM就绪状态以减少错误的可能性可能很重要。