How can I pause a Bootstrap Carousel on hover and resume it on mouse-out?

一曲冷凌霜 提交于 2019-12-02 02:41:53

问题


I have a Bootstrap Carousel on my website.

When the user hovers over an element #formcontainer, I'd like to pause the carousel. And when I hover off, I'd like to continue the cycle of the carousel. The first part works fine with the following code, but not the second. Can someone assist?

$(document).ready(function() {
    $('.carousel').carousel({
        interval: 1200,
        pause: "hover"
    });

    $('#formcontainer').hover(function(){
        $("#myCarousel4").carousel('pause');
    });
});

回答1:


Use carousel cycle method on mouseleave event

$('#formcontainer').hover(function(){
   $("#myCarousel4").carousel('pause');
},function(){
   $("#myCarousel4").carousel('cycle');
});



回答2:


jQuery's hover function has an implementation that takes two arguments: a hover in handler and a hover out handler:

$('#foo').hover(function() {
    // handler in
}, function() {
    // handler out
});

When you pass it just one argument, the function you give it handles both the in and out events, so you're pausing it on both mouse enter and mouse out.

You need to pass it separate handlers:

$('#myCarousel4').hover(function() {
    $(this).carousel('pause');
}, function() {
    $(this).carousel('cycle');
});

Note that we can use this to refer to the carousel rather than rewriting its ID. Inside jQuery event handlers, this always refers to the object you bound the event to when possible.




回答3:


This will work!

(function($) {
$(document).ready(function(){
    $('.carousel').carousel({
        pause: 'hover'
    });

}); }(jQuery));


来源:https://stackoverflow.com/questions/41061522/how-can-i-pause-a-bootstrap-carousel-on-hover-and-resume-it-on-mouse-out

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!