jQuery-mouseleave

时间:2018-12-04 00:49:37

标签: javascript jquery html css

下面有一个非常简单的代码。当我将鼠标悬停在一个小红色方块上时,会出现另一个大彩色方块。

问题:当我将光标移开这个大正方形时,这个正方形将被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();
  });

});

2 个答案:

答案 0 :(得分:1)

您只需在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>

答案 1 :(得分:0)

mouseleave具有函数as an argument

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