保持 JQuery 对话框在鼠标悬停时保持打开状态

6
我想在主页面上显示通知,为此我使用了JQuery对话框。我可以使用以下代码实现页面加载时的自动显示和隐藏。但是,如果鼠标悬停在对话框上,我想保持对话框打开状态。
$(document).ready(function () {

    $("#dialog").dialog({
        autoOpen: false,
        draggable: false,
        resizable: false,
        height: 100,
        hide: {
            effect: 'fade',
            duration: 2000
        },
        open: function () {
            $(this).dialog('close');
        },
        close: function(){
            // $(this).dialog('destroy');
        },
        show: {
            effect: 'fade',
            duration: 2000
        }
    });

    var x = $("#<%= imgNotifcation.ClientID %>").position().left + $("#<%= imgNotifcation.ClientID %>").outerWidth();
    var y = $("#<%= imgNotifcation.ClientID %>").position().top - jQuery(document).scrollTop();

    // var x = 0;

    $("#dialog").dialog("open");
    $('#dialog').dialog( 'option', 'position', [x-90, y+25] ); 

});

这个工作很好,但是它即使我将鼠标悬停在#dialog div上也会隐藏对话框。我希望它在悬停时保持打开状态。

我在这里看不到任何代码会在你悬停对话框时触发关闭。你确定你的代码全部都在这里吗? - Dan H
@Danny H..是的,整个代码都在这里。对话框关闭事件是在打开事件中编写的。 - Bharat Sisode
2个回答

0
请看这个例子。

var i = 0;
$(".overout")
  .mouseover(function() {
    i += 1;
    $(this).find("span").text("mouse over x " + i);
  })
  .mouseout(function() {
    $(this).find("span").text("mouse out ");
  });

var n = 0;
$(".enterleave")
  .mouseenter(function() {
    n += 1;
    $(this).find("span").text("mouse enter x " + n);
  })
  .mouseleave(function() {
    $(this).find("span").text("mouse leave");
  });
.out {
  width: 40%;
  height: 120px;
  margin: 0 15px;
  background-color: #d6edfc;
  float: left;
}

.in {
  width: 60%;
  height: 60%;
  background-color: #fc0;
  margin: 10px auto;
}

p {
  line-height: 1em;
  margin: 0;
  padding: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>

  <div class="out overout">
    <span>move your mouse</span>
    <div class="in">
    </div>
  </div>

  <div class="out enterleave">
    <span>move your mouse</span>
    <div class="in">
    </div>
  </div>


</body>

现在当你的鼠标放在那个 div 上时,只需执行你的对话框操作


0

在对话框显示后,您立即调用关闭函数。您无法通过这种方式停止它。您可以做的是设置一个计时器来关闭,当鼠标悬停时停止计时器并重新启动计时器,当鼠标离开对话框时。

您需要一个变量来存储关闭计时器:

var dialogCloseTimer = null;

在对话框配置中,使用1秒(1000毫秒)启动关闭定时器。
open: function ()  {
    var self = this;
    dialogCloseTimer = window.setTimeout(function() {
        $(self).dialog('close');
    }, 1000);
},

对话框配置完成后,为 mouseentermouseleave 事件设置监听器以停止和重新启动关闭计时器:

$("#dialog").on("mouseenter", function() {
    window.clearTimeout(dialogCloseTimer);
}).on("mouseleave", function() {
    var self = this;
    dialogCloseTimer = window.setTimeout(function() {
        $(self).dialog('close');
    }, 1000);
});

这就是我一直在寻找的东西。非常感谢! :-) - Bharat Sisode

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