【问题标题】:How can I have a jQuery hover event re-trigger on overlapping elements?如何在重叠元素上重新触发 jQuery 悬停事件?
【发布时间】:2016-12-03 16:38:48
【问题描述】:

我目前的一个函数在被 jQuery 悬停事件触发时触发。有些元素是通过 Javascript 添加到 DOM 中的,有些元素已经在 HTML 文件中。我的代码如下:

$('<a>').attr('href', '#').attr('class', 'icon').css('left', 4).html($('<img>').attr('src', 'http://i.imgur.com/bQFAeqi.png')).appendTo($('body'));

$('body').hover(function(e) {
    var firstClassName = $(e.target)[0].className.split(' ')[0];
    console.log(firstClassName);
  },
  function() {
    console.log('hover out')
  });
body {
  background-color: #000;
}
.panel {
  left: 4px;
  top: 34px;
  width: 150px;
  height: 150px;
  color: #000;
  background-color: #E0D0C8;
  position: absolute;
  border: thick solid #FFF;
  border-radius: 5px;
}
.icon {
  background-color: black;
  position: absolute;
  z-index: 2;
  border: 2px solid #FFF;
  border-radius: 1px;
  top: 4px;
}
.icon img {
  image-rendering: pixelated;
  image-rendering: optimizeSpeed;
  min-width: 32px;
  min-height: 32px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <div class="panel"></div>
</body>

意外的行为是,当我将鼠标悬停在一个元素上,然后将鼠标悬停在另一个重叠的元素上时,悬停事件不会重新触发。

例如,当我将鼠标悬停在与#text-panel 重叠的.icon 上时,只有当鼠标退出两个元素并且hover out 事件触发时,悬停事件才会重新触发。如何在不让鼠标退出所有重叠元素的情况下重新触发悬停事件?

【问题讨论】:

    标签: javascript jquery html css hover


    【解决方案1】:

    使用 $('body').on('mouseenter mouseleave', '.icon, .panel',function(e) 对确切的元素集使用相同的事件处理程序

    $('<a>').attr('href', '#').attr('class', 'icon').css('left', 4).html($('<img>').attr('src', 'http://i.imgur.com/bQFAeqi.png')).appendTo($('body'));
    
    $('body').on('mouseenter mouseleave', '.icon, .panel',function(e) {
        var firstClassName = $(e.target)[0].className.split(' ')[0];
        console.log(firstClassName+'-'+e.type);
      });
    body {
      background-color: #000;
    }
    .panel {
      left: 4px;
      top: 34px;
      width: 150px;
      height: 150px;
      color: #000;
      background-color: #E0D0C8;
      position: absolute;
      border: thick solid #FFF;
      border-radius: 5px;
    }
    .icon {
      background-color: black;
      position: absolute;
      z-index: 2;
      border: 2px solid #FFF;
      border-radius: 1px;
      top: 4px;
    }
    .icon img {
      image-rendering: pixelated;
      image-rendering: optimizeSpeed;
      min-width: 32px;
      min-height: 32px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <body>
      <div class="panel"></div>
    </body>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-01
      • 1970-01-01
      • 2015-07-10
      • 1970-01-01
      • 2012-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多