2014-09-28 79 views
0

我有这个代码适合我的目的,但它适用于单个幻灯片;与多个幻灯片,无论我将鼠标放置,它使所有的幻灯片上运行,这取决于同一类,但如果我尝试分配不同的类,它是一个烂摊子:多个幻灯片相同的脚本

function slideImages(){ 
     var $active = $('.portfolio_slider .active'); 
     var $next = ($('.portfolio_slider .active').next().length > 0) ? $('.portfolio_slider .active').next() : $('.portfolio_slider img:first'); 
     $next.css('z-index',2); 
     $active.css('z-index',1); 
     $next.animate({left:0},"fast",function(){ 

       $next.addClass('active'); 
     }); 
    } 

    $(document).ready(function(){ 

    $('.portfolio_slider').on('mouseover', function(){ 
     setInterval(slideImages, 400); 
     $(this).off('mouseover'); 

    }) 
}) 

CSS:

.portfolio_slider{position:relative; width:100px; height:250px; overflow:hidden;} 
.portfolio_slider img{position:absolute;left:100px;} 
.portfolio_slider img.active{left:0} 

我对js-jquery来说很新鲜......有什么帮助吗?

HTML:

<div class="portfolio_slider"> 
<img class="active" src="1.jpg" width="100" height="170"> 
<img src="2.jpg" width="100" height="170"> 
<img src="3.jpg" width="100" height="170"> 
<img src="5.jpg" width="100" height="170"> 
<img src="6.jpg" width="100" height="170"> 
<img src="1.jpg" width="100" height="170"> 

</div> 
+0

你能展示你的html代码来看幻灯片的结构吗? – 2014-09-28 05:26:59

回答

1

你应该通过您要使用的功能slideImages滑块,然后只用它的元素。

function slideImages(slider){ // slider is the element 
     var $active = $('.active', slider); // search for .active in this element 
     var $next = ($('.active', slider).next().length > 0) ? $('.active', slider).next() : $('img:first', slider); 
     $next.css('z-index',2); 
     $active.css('z-index',1); 
     $next.animate({left:0},"fast",function(){ 

       $next.addClass('active'); 
     }); 
    } 

    $(document).ready(function(){ 

    $('.portfolio_slider').on('mouseover', function(){ 
     var _this = this; // save it for other context 
     setInterval(function(){ 
      slideImages(_this); 
     }, 400); 
     $(this).off('mouseover'); 

    }); 
}); 
+0

如果我想让幻灯片在每个鼠标悬停上运行而不只是一次,该怎么办?或者如果我想为幻灯片显示不同的大小(div)? – dario 2014-09-28 05:55:02

+0

您可以删除'$(this).off('mouseover');'以便它可以运行多次。我不太明白你的第二个问题,你能澄清吗? – Scimonster 2014-09-28 05:56:06

+0

噢,删除'$(this).off('mouseover');'会导致它每次移动鼠标都会运行。您可能想要听[mouseenter](http://api.jquery.com/mouseenter/)事件。 – Scimonster 2014-09-28 05:57:13