【问题标题】:jQuery hover, onhover show another element and move the mouse backjQuery悬停,悬停时显示另一个元素并将鼠标移回
【发布时间】:2015-05-12 03:01:40
【问题描述】:

当悬停红色框时,将显示灰色框。如果鼠标停留在灰色框上,则灰色框保持打开状态。当将鼠标从灰色框移回红色框时,我希望灰色框仍然打开。

只有当鼠标没有悬停在红色或灰色框上时,灰色框才会关闭。

http://jsfiddle.net/0sLhL0xf/

唯一的问题是,当我将鼠标从灰色框移回红色框时,我无法让灰色停留显示。

有人可以帮忙吗?请不要改变结构,我知道用 box1 包裹 box2 更容易,

<div id="box1">
    <div id="box2"></div>
</div>

但这不是我想尝试的。谢谢

【问题讨论】:

  • 可以包含js 尝试过的问题吗?
  • 你需要超时吗?

标签: javascript jquery


【解决方案1】:

尝试使用css

#box1 {
    width: 40px;
    height: 40px;
    background: red;
    cursor:pointer;
}

#box2 {
    display:none;
    width: 400px;
    height: 400px;
    background: grey;
}

#box1:hover + #box2, #box2:hover {
    display:block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="box1"></div>
<div id="box2"></div>

jsfiddle http://jsfiddle.net/0sLhL0xf/3/

【讨论】:

  • 谢谢!但是,如果结构更改为 &lt;div id="mybox"&gt; &lt;div id="mybox_layer"&gt; &lt;div id="box1"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="box2"&gt;&lt;/div&gt;,则 css 将无法工作
  • @olo 也许更新原始帖子详细信息,jsfiddle jsfiddle.net/0sLhL0xf 在问题上反映html 以上的可能性? fwiw,css,稍作调整,可能会返回与上述html 相同的结果。干杯:)
  • 是的,会尝试的。非常感谢! :)
【解决方案2】:

我认为你可以使用

var timeout;
var $box1 = $('#box1');
var $box2 = $('#box2');

$box1.hover(function() {
  clearTimeout(timeout);
  $box2.show();
}, function() {
  timeout = setTimeout(function() {
    $box2.hide();
  }, 1000);
});

$box2.hover(function() {
  clearTimeout(timeout);
}, function() {
  timeout = setTimeout(function() {
    $box2.hide();
  }, 1000);
});
#box1 {
  width: 40px;
  height: 40px;
  background: red;
  cursor: pointer;
}
#box2 {
  display: none;
  width: 400px;
  height: 400px;
  background: grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="box1"></div>
<div id="box2"></div>

【讨论】:

    【解决方案3】:

    这是另一个使用 mouseentermouseleave 的解决方案。

    http://jsfiddle.net/0sLhL0xf/2/

    var $boxes = $('.boxes');
    var $box1 = $('#box1');
    var $box2 = $('#box2');
    
    $boxes.mouseenter(function() {
        $box2.show();
    });
    $boxes.mouseleave(function() {
        $box2.hide();
    });
    #box1 {
        width: 40px;
        height: 40px;
        background: red;
        cursor:pointer;
    }
    
    #box2 {
        display:none;
        width: 400px;
        height: 400px;
        background: grey;
    }
    <div class="boxes" id="box1"></div>
    <div class="boxes" id="box2"></div>
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    【讨论】:

    • 在此处发布代码,而不仅仅是在小提琴中。为什么不使用堆栈 sn-p,这样这里的代码就可以像小提琴一样执行?
    • @Barmar 我的错,添加了 sn-p。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-02
    • 1970-01-01
    • 2018-03-04
    • 2013-06-30
    • 2011-08-04
    • 1970-01-01
    • 2017-03-06
    相关资源
    最近更新 更多