【问题标题】:javascript onmouseover+onmouseout and relation between 2 divsjavascript onmouseover+onmouseout 和 2 个 div 之间的关系
【发布时间】:2013-09-15 17:03:19
【问题描述】:

我正在尝试制作一个功能,以便在鼠标悬停时显示按钮并在鼠标悬停时隐藏。 以下示例将显示我的问题。

------------------------------------------------------------


 ---------
| button2 |           DIV#1                 Button1
|         |
| DIV#2   |
|         |
----------------------------------------------------------
|         |
-----------

**The CSS** 
#div1{

    height: 200px;
    width:500px;
    position: relative;
}
#div2{
    height: 150px;
    width: 150px;
    left: 19px;
    top: 76px;
    position: absolute;
}


**Javascript**
$("#button1").hide();
$("#button2").hide();

$('#div1').mouseover(function() {
$("#button1").show();
});

$('#div1').mouseout(function() {
$("#button1").hide();
});

$('#div2').mouseover(function() {
$("#button2").show();
});

$('#div2').mouseout(function() {
$("#button2").hide();
});

HTML 实际上,我的文档中有很多元素。但为了便于查看:

<div id='div1'>  <div id='div2'>example button2 </div> example button1 </div>

问题是:

当鼠标悬停在 DIV#2 上时,Button1 也会显示。看起来这 2 个 div 彼此相关。 如何解决此问题以使 Buttun1 仅在鼠标悬停在 DIV#1 上时显示。

我尝试使用 z-index,但没有帮助。

【问题讨论】:

  • 你也可以添加 HTML 吗?
  • 这有点困难,因为那里有很多元素。但无论如何我有更新,请看上面。

标签: javascript css


【解决方案1】:

假设div2div1 之上,问题是当您将鼠标放在两个div 重叠的区域时,两个div 都会获得鼠标悬停事件。您可以在#div2 上停止事件传播,这样当鼠标进入div2 上方并进入重叠区域时,鼠标悬停不会冒泡到底层div1

$('#div2').mouseover(function(event) {
    $("#button2").show();
    event.stopPropagation();// this will stop mouseover on other div
});

同样,当鼠标从div1 移动到div2 时,您可能需要添加代码来删除button1,而不会离开不可靠的div1,即重叠区域。

$('#div2').mouseover(function(event) {
    $("#button1").hide();
    $("#button2").show();
    event.stopPropagation();
});

【讨论】:

  • 非常感谢,我花了一整天的时间来写这些话。
【解决方案2】:

如果 div 2 是 div 1 的子项,则 div 2 上的悬停事件会冒泡到 div 1。您需要做的是使用 event.stopPropagation() 来防止冒泡:

/* CSS */
#button1, #button2 {
    display: none;
}

/* jQuery */

$(function() {

    $('#div2').hover(
        function(event) {
            event.stopPropagation();
            $('#button2').toggle();
        },
        function(event) {    
            event.stopPropagation();   
            $('#button2').toggle();
        });

    $('#div1').hover(
        function() {
            $('#button1).toggle();
        },
        function() {
            $('#button2').toggle();
        });


});

【讨论】:

  • 非常感谢,虽然我得到了答案,但这个也很高兴尝试。我想为我的教育保留两个答案。再次感谢您。
猜你喜欢
  • 2012-02-04
  • 1970-01-01
  • 2011-06-27
  • 1970-01-01
  • 2011-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多