首页 > 解决方案 > jQuery - 鼠标离开

问题描述

我在下面有一个非常简单的代码。当我悬停其中一个红色小方块时,会出现另一个大颜色方块。

问题:当我将光标移开这个大方块时,这个方块会被 隐藏mouseleave().hide(),但它不起作用。

请帮忙。

jsfiddle

HTML

<table class="table" style="width:100%">

  <tr>
    <td>
      <div class="hot-spot" data-target="black"></div>
      <div ID="black"></div>
    </td>
    <td>
      <div class="hot-spot" data-target="green"></div>
      <div ID="green"></div>
    </td>
        <td>
      <div class="hot-spot" data-target="blue"></div>
      <div ID="blue"></div>
    </td>
    <td>
      <div class="hot-spot" data-target="yellow"></div>
      <div ID="yellow"></div>
    </td>
  </tr>

</table>

JS

$(function() {
    $('.hot-spot').hover(function (e) {
    var square = $(this).data('target');
    $('#' + square).show();
    $('#' + square).mouseleave.hide();
  });

});

标签: javascriptjqueryhtmlcss

解决方案


您只需要在 mouseleave 之后添加括号以显示它是一个函数:

$(function() {
  $('.hot-spot').hover(function(e) {
    var square = $(this).data('target');
    $('#' + square).show();
    $('#' + square).mouseleave(function() {
      $('#' + square).hide();
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table" style="width:100%">

  <tr>
    <td>
      <div class="hot-spot" data-target="black">a</div>
      <div ID="black">black</div>
    </td>
    <td>
      <div class="hot-spot" data-target="green">b</div>
      <div ID="green">green</div>
    </td>
    <td>
      <div class="hot-spot" data-target="blue">c</div>
      <div ID="blue">blue</div>
    </td>
    <td>
      <div class="hot-spot" data-target="yellow">d</div>
      <div ID="yellow">yellow</div>
    </td>
  </tr>

</table>


推荐阅读