1

div如果鼠标悬停在 div 或任何嵌套元素上,我想显示工具栏。但是以下使用 jQuery 1.7 的解决方案仅在鼠标div直接悬停时才有效,只有在我将 a 添加paddingitemcss 类时才有可能。

<head>
  <script type="text/javascript" src="jquery-1.7.min.js"></script>
  <style type="text/css">
    .toolbar { display: none; }
    .item { padding: 1px; } /* doesn't work without padding! */
  </style>
  <title>Demo</title>
</head>

    <body>

  <div class="section">
    <div class="item">
      <p class="toolbar">TOOLS</p>
      <p>content</p>
    </div>
    <div class="item">
      <p class="toolbar">TOOLS</p>
      <p>content</p>
    </div>
  </div>

  <script type="text/javascript">
    $(".section").on(
      "mouseenter",
      ".item",
      function(event) {

        $(event.target).children('.toolbar')
          .show(100);
      }
    )

    $(".section").on(
      "mouseleave",
      ".item",
      function(event) {
        $(event.target).children('.toolbar').hide();
      }
    )      
  </script>

</body>

1px 的填充不会那么糟糕,但它会导致顶部和底部的填充更大,并且此解决方法无法正常工作 - 尤其是当鼠标从左侧或右侧进入时。

如何在没有填充技巧的情况下处理事件mouseentermouseleave

4

4 回答 4

2

我创建的这个小提琴没有填充就可以正常工作。也许你只需要调整一些小的东西(比如在 CSS 链中继承的宽度)。

如果这不能为您解决问题,请给我们一个重现问题的小提琴,以便我们为您修改它。

于 2011-11-18T22:39:32.420 回答
2

似乎event.target不是 div - 更改以$(this)解决问题 - > http://api.jquery.com/event.target/

http://jsfiddle.net/manseuk/StUvz/

于 2011-11-18T22:44:33.193 回答
0

这一项没有填充也可以工作http://jsfiddle.net/rkpVW/你可以直接做一个 on(".item") 我认为这是绑定元素的最简单的解决方案。

编辑: http: //jsfiddle.net/rkpVW/1/使用实时动态内容

于 2011-11-18T22:49:03.580 回答
0

使用$(event.currentTarget)将解决问题,并且表现相同,$(this)只是更好,因为它会在其他情况下继续工作this

init: function()
{
    $("button").on("mouseenter", this.proxy(function(event)
    {
        this.classMethod();

        console.log( event.currentTarget );
    }) );
}

如您所见,event.currentTarget this

$("button").on("mouseenter", function(event)
{
    console.log( event.currentTarget === this );
});
于 2013-06-16T06:18:37.970 回答