Jquery简单的无限循环滑块逻辑
Posted
技术标签:
【中文标题】Jquery简单的无限循环滑块逻辑【英文标题】:Jquery simple infinite loop slider logic 【发布时间】:2019-05-25 17:18:51 【问题描述】:我是 Jquery 的新手,我制作了一个简单的静态滑块,其中包含五个具有相同类名 (.sl_thumb) 的图像 这是下一个和上一个锚的代码—— 右锚 (.right_nav_link)、左锚 (.left_nav_link) 幻灯片主 div(.slide_container)
我的上一个和下一个链接工作正常,但是当滑块到达最后一张幻灯片时它会停止,我正在尝试制作无限循环滑块,以便它应该在最后一张之后再次到达第一张幻灯片。作为初学者,我尝试了很多事情,但很困惑,我可以使用的最佳逻辑是什么。
$(document).ready(function ()
var src = 'img/img1.jpg';
$(".right_nav_link").click(function ()
var next = false;
$($("img").filter(".sl_thumb")).each(function (key, value)
if ($(this).attr('src') == src)
next = true;
else if (next)
next = false;
src = $(this).attr('src');
$(".slide_container").css('background-image', 'url(' + src + ')');
return;
);
);
$(".left_nav_link").click(function ()
var prev = false;
$($("img").filter(".sl_thumb").get().reverse()).each(function (key, value)
// console.log(key,value);
if ($(this).attr('src') == src)
prev = true;
else if (prev)
prev = false;
src = $(this).attr('src');
$(".slide_container").css('background-image', 'url(' + src + ')');
return;
);
);
);
【问题讨论】:
如果您将其更改为在活动元素上放置一个类(如“活动”),然后当您单击下一个或上一个时,您的逻辑会更简单图像并使其处于活动状态,当您到达任一侧时旋转回开始/结束。 但是,事实上,问题在于您的逻辑将 next/prev 设置为 true,但这是最后一次迭代,因此不会发生 else。如果你想保持这个逻辑,你需要一些其他的变量来检查你是否真的改变了图像。如果您在循环后没有更改它,那么您将执行“重置”逻辑回到另一端 先生,完成后如何重置each(),我是这样想的,但无法实现。我希望我应该检查 each(value) 是否达到我应该重置 each() 的最后一个。那可能吗?。对不起任何愚蠢的事情 【参考方案1】:$( document ).ready(function()
var src = 'img/img1.jpg';
function adjustSlideContainer ( adjustPositionAmount )
//get all the images
var $thumbnails = $( 'img.sl_thumb' );
//find the current one shown
var $current = $thumbnails.filter( '[src="'+ src +'"]' );
//get its index
var currentIndex = $thumbnails.index( $current );
//adjust the index to the image that should be shown next
var nextIndex = currentIndex + adjustPositionAmount;
if ( nextIndex < 0 )
//if it's before the first one, wrap to the last one
nextIndex = $thumbnails.length - 1;
else if ( nextIndex >= $thumbnails.length )
//if it's after the end one, wrap to the first one
nextIndex = 0;
src = $thumbnails.eq( nextIndex ).attr( 'src' );
$( '.slide_container' ).css( 'background-image', 'url(' + src + ')' );
$(".right_nav_link").click(function()
//go to the next image
adjustSlideContainer( 1 );
);
$(".left_nav_link").click(function()
//go to the previous image
adjustSlideContainer( -1 );
);
);
【讨论】:
非常感谢先生,@Taplar,这工作正常,可能是正确的方法。我需要编写越来越多的代码来自己开发这些逻辑。再次感谢,迟来的圣诞快乐! @user9437856 并非所有的 sn-ps 都必须是可运行的。在这种情况下,cmets 应该足以解释它在做什么。鉴于 OP 接受了答案,这足以解决他们的问题。以上是关于Jquery简单的无限循环滑块逻辑的主要内容,如果未能解决你的问题,请参考以下文章