帮助自动旋转无限循环的jquery走马灯。无法使走马灯无限循环,而不是“倒带”。

7
我正在使用jquery构建一个自动旋转的图片轮播,我想让图片无限循环,而不是在到达最后一张图片时“倒带”回到第一张图片并重新开始。 不幸的是,我对jquery游戏还很陌生,所以我在尝试使其工作时遇到一些问题。 我已经尝试从网上教程中找到代码,并将其修改为适合我的代码,但没有成功。 我认为我可能需要克隆现有的图像,使它们在经过周期后出现,但我不确定要走哪个方向。 非常感谢任何帮助。 下面是我正在使用的代码:

HTML:

<div class="main_view">
    <div style="width:165px; height:98px; margin:0; padding:0; border:0;">
        <img src="/content/template_images/wanalogo-blackBG-165x98.png" />
    </div>
    <div class="window">
        <ul class="image_reel">
        <li><a href="/MLB/Philadelphia-Phillies-Tickets" title="Phillies"><img src="/content/template_images/Banners/SideBanner/imgscroll1.jpg" alt="Phillies" /></a></li>
        <li><a href="/NFL/Philadelphia-Eagles-Tickets" title="Eagles"><img src="/content/template_images/Banners/SideBanner/imgscroll2.jpg" alt="Eagles" /></a></li>
        <li><a href="/NHL/Philadelphia-Flyers-Tickets" title="Flyers"><img src="/content/template_images/Banners/SideBanner/imgscroll3.jpg" alt="Flyers" /></a></li>
        <li><a href="/NBA/Philadelphia-76ers-Tickets" title="76ers"><img src="/content/template_images/Banners/SideBanner/imgscroll4.jpg" alt="76ers" /></a></li>
        <li><a href="/NCAA-Basketball" title="NCAA Basketball"><img src="/content/template_images/Banners/SideBanner/imgscroll8.jpg" alt="NCAA Basketball" /></a></li>
        <li><a href="/Concerts-Tickets" title="Concerts"><img src="/content/template_images/Banners/SideBanner/imgscroll5.jpg" alt="Concerts" /></a></li>
        <li><a href="/Theatre-Tickets" title="Theatre"><img src="/content/template_images/Banners/SideBanner/imgscroll6.jpg" alt="Theatre" /></a></li>
        <li><a href="/Other-Events-Tickets" title="Family Events"><img src="/content/template_images/Banners/SideBanner/imgscroll7.jpg" alt="Family Events" /></a></li>
        </ul>
    </div>
    <div style="width:170px; height:290px; border:0; padding:0; margin: -290px 0px 0px 0px;">
        <img src="/content/template_images/black-fade-border-170x290.png" />
    </div>
    <div class="botTextBox">
        <center>
        <div class="botText">
        <a href="/MLB/Philadelphia-Phillies-Tickets" title="Phillies">Phillies</p></a>
        <a href="/NFL/Philadelphia-Eagles-Tickets" title="Eagles"><p>Eagles</p></a>
        <a href="/NHL/Philadelphia-Flyers-Tickets" title="Flyers"><p>Flyers</p></a>
        <a href="/NBA/Philadelphia-76ers-Tickets" title="76ers"><p>76ers</p></a>
        <a href="/NCAA-Basketball" title="NCAA Basketball"><p>NCAA Basketball</p></a>
        <a href="/Concerts-Tickets" title="Concerts"><p>Concert</p></a>
        <a href="/Theatre-Tickets" title="Theatre"><p>Theatre</p></a>
        <a href="/Other-Events-Tickets" title="Family Events"><p>Family Event</p></a>
        </div>
        </center>
    </div>
        <div class="paging">
        <a href="#" rel="1">1</a>
        <a href="#" rel="2">2</a>
        <a href="#" rel="3">3</a>
        <a href="#" rel="4">4</a>
        <a href="#" rel="5">5</a>
        <a href="#" rel="6">6</a>
        <a href="#" rel="7">7</a>
        <a href="#" rel="8">8</a>
        </div>
</div>

Javascript

$(document).ready(function() {
    $(".paging").show();
    $(".paging a:first").addClass("active");

    var imageWidth = $(".window").width();
    var imageSum = $(".image_reel img").size();
    var imageReelWidth = imageWidth * imageSum;

    $(".image_reel").css({'width' : imageReelWidth});

    rotate = function(){
    var triggerID = $active.attr("rel") - 1; //Get number of times to slide
    var image_reelPosition = triggerID * imageWidth; //Determines the distance the image reel needs to slide

    $(".paging a").removeClass('active'); //Remove all active class
    $active.addClass('active'); //Add active class (the $active is declared in the rotateSwitch function)

    //Slider Animation
    $(".image_reel").animate({
        left: -image_reelPosition
    }, 750 );
    $(".botText").animate({
    left: -image_reelPosition
    }, 750 );
    }; 

    //Rotation  and Timing Event
    rotateSwitch = function(){
    play = setInterval(function(){ //Set timer - this will repeat itself every X seconds
    $active = $('.paging a.active').next(); //Move to the next paging
    if ( $active.length === 0) { //If paging reaches the end...
    $active = $('.paging a:first'); //go back to first
    }
    rotate(); //Trigger the paging and slider function
    }, 1500); //Timer speed in milliseconds (7 seconds)
    };

    rotateSwitch(); //Run function on launch

    //On Hover
    $(".image_reel a").hover(function() {
        clearInterval(play); //Stop the rotation
    }, function() {
        rotateSwitch(); //Resume rotation timer
    }); 

    //On Click
    $(".paging a").click(function() {
        $active = $(this); //Activate the clicked paging
        //Reset Timer
        clearInterval(play); //Stop the rotation
        rotate(); //Trigger rotation immediately
        rotateSwitch(); // Resume rotation timer
        return false; //Prevent browser jump to link anchor
    });
});

Edit- CSS:

.main_view {
    float: left;
    overflow:hidden;
    position: relative;
    width:170px; 
    height:475px; 
    background-color:black; 
    border:0; 
    margin:2px; 
    padding:2px 0px 2px 0px; 
    text-align:center;
}
.window {
    height:290px;   width:170px;
    overflow: hidden;
    position: relative;
    background-color:black; 
    border:0; 
    padding:0px; 
    margin:0px;
}
.image_reel {
    position: absolute;
    top: 0; left: 0;
    margin-left:-40px;
}
.image_reel img {float: left;}

.botTextBox {
    height:87px; width:1360px;
    overflow:hidden;
    position:relative;
    background:url(/content/template_images/black-side-bottom-170x87.png) no-repeat; 
    margin:0px; 
    padding:0px;
}
.botText {
    position:relative;
    top:0; left:0;
    margin:32px 0px 0px 0px; 
    padding:0; 
    text-align:center;
}
.botText p {width:170px; float: left;}

.paging {
    position: absolute;
    bottom: 40px; right: -7000px;
    width: 178px; height:47px;
    z-index: 100; 
    text-align: center;
    line-height: 40px;
    display: none; 
}
.paging a {
    padding: 5px;
    text-decoration: none;
    color: #fff;
}
.paging a.active {
    font-weight: bold;
    background: #920000;
    border: 1px solid #610000;
    -moz-border-radius: 3px;
    -khtml-border-radius: 3px;
    -webkit-border-radius: 3px;
}
.paging a:hover {font-weight: bold;}

实际上,您可以在右侧看到我正在尝试用jQuery替换的Flash横幅...

再次感谢您的帮助。就像我说的,我对使用jQuery还比较新手,我已经在这个问题上摸索了一整天。非常感谢。


你能提供一些CSS吗?你一次展示多少张图片?图片有多大?等等... - Mottie
看起来你正在移动一大块图像,所以当你回到第一个图像时,就会出现“倒带”的效果。为了让它看起来像是无限循环,请先添加一张图片,将下一张图片添加到DOM中。滑动到它。删除前一个图像,然后不断重复这个过程。 - Peter Ajtai
@fudgey:使用CSS进行编辑,并附上我目前的链接...@Peter Ajtai:有什么建议吗?抱歉,我的JavaScript不是很好... - garr1s0n
2个回答

4
你的旋转木马问题在于图片块仍然是一个巨大的块,因此当你到达结尾时,必须将其全部滑回第一张图片以进行循环,这就导致了那种“倒带”的外观。
我会这样做:
1. 将每个图像加载到数组中 2. 从库中删除除第一个图像以外的所有图像。 3. 添加下一张图像(在循环中,数组下一个值为 number % length) 4. 动画滑块以显示下一张图像 5. 重置CSS并删除现在不可见的第一张图像 6. 再来一遍。
以下是具有递归函数的示例实现。
我创建了一个滑块函数,利用了jQuery的.animate()。在.animate()的回调中,我通过setTimeout()引起了短暂的暂停,然后再次调用滑块函数。
以下示例非常简单,您可以轻松调整它,例如显示前一个和下一个图像的片段以及其他内容... 这只是为了说明有限数量的图像的无限滑动的简单实现。
我添加了一个简单的实现方式,用于在画廊下方显示变化的标题。标题的信息取自图像的HTML代码。该标题也可以放置在每个图像下方,并随图像一起滑动。

jsFiddle示例

$(function() {          
    var showing = 0;    // which image is showing
    var imgs = [];      // array to hold images HTML
      // Put image elements into an array
    imgs = $("#gallery img").toArray();
    var numberOf = imgs.length;    
      // Remove all but first image from DOM
    $("#slider").html("");
    $("#slider").html(imgs[0]);    
      // Add title text div
    $("#gallery").after('<a id="title"/>');
      // The recursive slider function
    var nextImage = function() {
          // Add next image (only use increment once!)
        $("#slider").append(imgs[++showing % numberOf]);
          // Show image title
        $("#title").html($(imgs[showing % numberOf]).attr("title"));
          // Link to original
        $("#title").attr("href", $(imgs[showing % numberOf]).attr("src"));
          // Animate the slider
        $("#slider").animate({
            left: '-=200'
        }, 2000, function() {            
              // Remove image to the left
            $("#slider img:first").remove();            
              // Reset CSS
            $("#slider").css("left", "0px");            
              // Call animationg function again
            setTimeout(function() {nextImage(); }, 1000);
        });  
    }        
    nextImage();  // Call next image for the first time         
});

静态HTML将包括:
<div id="gallery">
    <div id="slider">
        ... the images here ...
    </div>
</div>

提示: 想要查看传送带效果的工作原理,请点击这里


使用的jQuery和JS方法及属性:

  • .animate():使用jQuery的动画效果来改变元素的样式属性。
  • .append():将指定内容添加到元素的结尾处。
  • .css():设置或返回元素的CSS属性。
  • :first selector:选择匹配元素集合中的第一个元素。
  • .html():设置或返回元素的HTML内容。
  • .length:返回元素集合的长度。
  • .remove():从DOM中删除元素。
  • setTimeout():在指定的时间后执行一次函数。
  • .toArray():将元素集合转换为JavaScript数组。

1
+1 对于值得收录在维基百科的答案。文档和所有内容都已提供 XD。 - Moses

1

Peter Ajtai有一个不错的方法总结,但我有另一种方法,只需要在脚本中添加几行代码。

基本上,它会克隆第一张图片、文本和分页链接,并将其添加到末尾。当动画结束在最后一张图片(现在实际上是第一张)时,窗口的左侧定位将重置为零,动画将继续播放。我尝试使用[NEW]添加注释,以便您更轻松地找到更改内容。而且,我制作了演示,希望这样更清楚明白。

$(document).ready(function() {
 $(".paging").show();
 $(".paging a:first").addClass("active");

 var imageWidth = $(".window").width();
 // [NEW] add one, since we are adding the first image to the end
 var imageSum = $(".image_reel img").size() + 1; 
 var imageReelWidth = imageWidth * imageSum;

 // [NEW] included modifying width of botTextBox 
 $(".image_reel, .botTextBox").css({'width' : imageReelWidth });

 // [NEW] clone first image & text and add it to the end, include dummy paging
 $(".image_reel li:first").clone().appendTo( $(".image_reel") );
 $(".botText a:first").clone().appendTo( $(".botText") );
 $(".paging").append('<a href="#" rel="' + imageSum + '"></a>'); // don't include the number in the link

 rotate = function(){
  var triggerID = $active.attr("rel") - 1; //Get number of times to slide
  var image_reelPosition = triggerID * imageWidth; //Determines the distance the image reel needs to slide

  $(".paging a").removeClass('active'); //Remove all active class
  $active.addClass('active'); //Add active class (the $active is declared in the rotateSwitch function)

  // [NEW] Slider Animation
  $(".image_reel, .botText").animate({
   left: -image_reelPosition
  }, 750, function(){
   // [NEW] callback function (called when animation is done)
   if (triggerID == imageSum - 1) {
    // if we're back to the first image, reset the window position
    $(".image_reel, .botText").css('left',0);
   }
  });
 };

 //Rotation  and Timing Event
 rotateSwitch = function(){
  play = setInterval(function(){ //Set timer - this will repeat itself every X seconds
   $active = $('.paging a.active').next(); //Move to the next paging
   if ( $active.length === 0) { // If paging reaches the end...
    // [NEW] go back to second image (the first is now the last)        
    $active = $('.paging a:eq(1)');
   }
   rotate(); //Trigger the paging and slider function
  }, 1500); //Timer speed in milliseconds (7 seconds)
 };

 rotateSwitch(); //Run function on launch

 //On Hover
 $(".image_reel a").hover(function(){
  clearInterval(play); //Stop the rotation
 }, function(){
  rotateSwitch(); //Resume rotation timer
 }); 

 //On Click
 $(".paging a").click(function() {
  $active = $(this); //Activate the clicked paging
  //Reset Timer
  clearInterval(play); //Stop the rotation
  rotate(); //Trigger rotation immediately
  rotateSwitch(); // Resume rotation timer
  return false; //Prevent browser jump to link anchor
 });

});

哦,最后一件事...我在Phillies botText前面添加了缺失的<p>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接