【问题标题】:jQuery hover two divs with different eventsjQuery悬停两个具有不同事件的div
【发布时间】:2014-09-18 08:43:43
【问题描述】:

我创建了一个显示当前天气的 div 和一个显示 5 天预报的弹出 div。

这是我的 jQuery 代码:

    $('.weather-popup').hide();
    $('.weather-current,.weather-popup').click(function(event){ 
    $('.weather-popup').toggle(400);
        event.stopPropagation();
    });

    $("html").click(function() {
    $(".weather-popup").hide(300);
    }); 

.weather-current 是显示当前天气的 div,.weather-popup 显示 5 天的预报。

使用 .click() 函数效果很好,但是如何使用 .hover() 函数来完成呢?

首先我尝试过这样的:

$(".weather-current").hover(function(){
    $('.weather-popup').stop().show(500);
    }, function(){
        $('.weather-popup').stop().hide(500);
    });

当我将鼠标悬停在 .current-weather 上时,.weather-popup 会正确显示,但是当我将鼠标悬停在 .weather-popup 上时,div 当然会隐藏起来。

当我将鼠标悬停在 .weather-current 上时,如何设置该组合,.weather-popup 将显示,然后当我将鼠标悬停在 .weather-current 上时,该 div 保持打开状态?

【问题讨论】:

    标签: jquery hover


    【解决方案1】:

    您可以使用计时器来隐藏weather-currentmouseleave 上的弹出窗口

    jQuery(function ($) {
        $(".weather-current").hover(function () {
            var $target = $('.weather-popup');
            clearTimeout($target.data('hoverTimer'));
            $target.stop(true, true).slideDown(500);
        }, function () {
            var $target = $('.weather-popup');
            var timer = setTimeout(function () {
                $target.stop(true, true).slideUp();
            }, 200);
            $target.data('hoverTimer', timer);
        });
    
        $('.weather-popup').hover(function () {
            clearTimeout($(this).data('hoverTimer'));
        }, function () {
            $(this).stop(true, true).slideUp();
        });
    });
    .weather-popup {
        display:none;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <div class="weather-current">weather-current</div>
    <div class="weather-popup">weather-popup</div>

    【讨论】:

      【解决方案2】:

      这可能是因为在您的 HTML 代码中 div.weather-popup 不是 div.weather-current 的子代。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-12
        • 1970-01-01
        • 1970-01-01
        • 2016-01-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多