为什么'keyup'事件无法在CSS中进行更改?

Ami*_*dat 0 html javascript css jquery

mouseleave事件能够进行CSS更改,但是当ALT释放密钥时,keyup事件不会执行它应该进行的CSS更改.它干扰了mouseenter吗?如果是,那么如何解决问题?

$(document).on('mouseleave', '.el', function(e) {
  $(this).css("background-color", "white");
  $(this).css("color", "black");

});

$(document).on('keyup', '.el', function(e) {
  if (e.altKey) {
    $(this).css("background-color", "white");
    $(this).css("color", "black");

  }
});

$(document).on('mouseenter keypress', '.el', function(e) {
  if (e.altKey) {

    $(this).css("background-color", "#99DCFC");
    $(this).css("color", "red");

  }

});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="t1" align="center" border=1>
  <tr>
    <th>First Name</th>
    <th>Last Name</th>
    <th>Email Address</th>
    <th>Telephone Number</th>
  </tr>
  <tr id="r">
    <tbody>
      <td id="d1" class="el" contenteditable="true"></td>
      <td id="d2" class="el" contenteditable="true"></td>
      <td id="d3" class="el" contenteditable="true"></td>
      <td id="d4" class="el" contenteditable="true"></td>
      <td>
        <button id="del1">Delete</button>
      </td>
    </tbody>
  </tr>
</table>
Run Code Online (Sandbox Code Playgroud)

nnn*_*nnn 5

您的代码有两个问题:

  1. 在keyup事件e.altKey中将是false因为alt键刚刚发布.尝试通过测试实际的密钥代码e.which.

  2. 在事件处理程序中,this将引用事件发生的元素,这似乎是显而易见的,除了该元素不一定是鼠标所在的元素:对于键事件,它将始终是具有(键盘的元素) )当时的重点.对此最简单的解决方法是使用类而不是单独设置CSS属性,因为这样您只需通过说$(".highlight")而不是从当前具有的任何元素中删除该类$(this).因此,您也不需要委托事件处理程序keyup,因为当时焦点可能不在任何有问题的元素上.

$(document).on('mouseleave', '.el', function(e) {
  $(this).removeClass("highlight");
});

$(document).on('keyup', function(e) {
  if (e.which === 18) {
    $(".highlight").removeClass("highlight");
  }
});

$(document).on('mouseenter keypress', '.el', function(e) {
  if (e.altKey) {
    $(this).addClass("highlight");
  }
});
Run Code Online (Sandbox Code Playgroud)
.highlight {
  background-color: #99DCFC;
  color: red;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="t1" align="center" border=1>
  <tr>
    <th>First Name</th>
    <th>Last Name</th>
    <th>Email Address</th>
    <th>Telephone Number</th>
  </tr>
  <tr id="r">
    <tbody>
      <td id="d1" class="el" contenteditable="true"></td>
      <td id="d2" class="el" contenteditable="true"></td>
      <td id="d3" class="el" contenteditable="true"></td>
      <td id="d4" class="el" contenteditable="true"></td>
      <td>
        <button id="del1">Delete</button>
      </td>
    </tbody>
  </tr>
</table>
Run Code Online (Sandbox Code Playgroud)

另请注意,使用类来设置颜色比在单独的函数中重复颜色代码要简洁.

(我认为以上仍然是一个小小的车,但它应该让你更接近你想要的位置.)