我是 jQuery 新手,正在练习幻灯片并尝试重复它。由于某种原因 if (last.is(active))
永远不会返回 true。在检查器中,我可以看到最后一个 child 正在获取事件 ID。这不是它的用途吗? if (active != last)
也不起作用。
JS
function changeImage() {
var active = $('#active');
var first = $('#slideshow:nth-child(1)');
var last = $('#slideshow:nth-last-child(1)');
if ( last.is(active) ) {
var next = first;
} else {
var next = active.next();
}
next.attr('id', 'active');
active.attr('id', 'inactive');
}
setInterval(changeImage, 1000);
标记
<div id="slideshow">
<img id="active" src="https://i.imgur.com/8iOuvtf.jpg">
<img src="https://i.imgur.com/Wi8mlH2.jpg">
<img src="https://i.imgur.com/MNhgqco.jpg">
</div>
CSS
#slideshow img {display: none;}
#slideshow #active {
display: block;
width: 100%;
height: auto;
}
最佳答案
我为你准备了这个 fiddle 。 https://jsfiddle.net/76xg0d7L/
在这种情况下,使用类比使用 ID 容易得多。我修改了你的changeImage()函数。
function changeImage() {
var $next = $('.slide.active').removeClass('active').next('.slide');
if ($next.length) {
$next.addClass('active');
}
else {
$('.slide:first').addClass('active');
}
}
setInterval(changeImage, 1000);
我还更新了您的 CSS 以选择事件类,而不是 ID。
#slideshow img {display: none;}
#slideshow .active {
display: block;
width: 100%;
height: auto;
}
如果您有任何疑问或者这是否适合您,请告诉我。
关于javascript - .is() 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33466881/