如何将鼠标悬停在幻灯片上暂停幻灯片

How to pause a slideshow by hovering over it

本文关键字:幻灯片 暂停 悬停 鼠标      更新时间:2023-09-26

好的,我有幻灯片工作,但我不知道如何判断鼠标是否悬停在图像上。

Javascript:

<script type="text/javascript">     
    var hovering = false;
    $('#slideshow').hover(function () {   //not sure if #slideshow is the right thing to put here
        hovering = true;
    }, function () {
        hovering = false;
        slideShow();
    });
    $(document).ready(function(){
        slideShow();
    });
    function slideShow() {
        if(!hovering) {
            var showing = $('#slideshow .show');
            var next = showing.next().length ? showing.next() : showing.parent().children(':first');
            var timer;
            showing.fadeOut(500, function() { next.fadeIn(200).addClass('show'); }).removeClass('show');
            setTimeout(slideShow, 3000);
        }
    }
</script>
HTML:

<div id="slideshow">
    <img class="show" src="../images/food/chicken_quesa.jpg">
    <img src="../images/food/beet_salad.jpg">
    <img src="../images/food/pasta_display.jpg">
</div>

试试:

$(document).ready(function() {
    var timer;
    $("#slideshow div").hide();
    $("#slideshow")
        // when mouse enters, clear the timer if it has been set
        .mouseenter(function() {
            if (timer) { clearInterval(timer) }
        })
        // when mouse goes out, start the slideshow
        .mouseleave(function() {
            timer = setInterval(function() {
                $("#slideshow > div:first")
                    .fadeOut(1000)
                    .next()
                    .fadeIn(1000)
                    .end()
                    .appendTo("#slideshow");
            }, 3000);
        })
        // trigger mouseleave for initial slideshow starting
        .mouseleave();
});​

使用mouseenter and mouseleave:

$('#slideshow').mouseenter(function () {
    hovering = true;
}).mouseleave(function () {
    hovering = false;
    slideShow();
});

阅读文档鼠标进入和鼠标离开