jQuery CSS 更改仅在点击时有效?

jQuery CSS on change works only on click?

我在函数中创建的'buttons'的初始设置是这样的。

$(".save_w").css("color", "grey");
$(".save_w").css("pointer-events", "none");

HTML(简体):

<input class="input_w" type="text">

<i class="save_w far fa-save"></i>

接下来,功能很简单:

$('body').on('change', '.input_w', function() {
  console.log("change");

  $(".save_w").css("pointer-events", "auto");
  $(".save_w").attr("color", "");
});

我想达到的目标

用class改变输入值后"input_w"".save_w"的css应该改变。

我得到了什么

当我更改输入值时,".save_w" 会发生变化,但只有在我点击网站上的某处后才会发生变化(通常我会点击另一个元素来触发变化)。为什么?这里没有onclick方法

change 事件仅在通过离开表单字段提交更改后触发:

The change event is fired for <input>, <select>, and <textarea> elements when an alteration to the element's value is committed by the user. Unlike the input event, the change event is not necessarily fired for each alteration to an element's value.

Depending on the kind of element being changed and the way the user interacts with the element, the change event fires at a different moment:

[...]

  • When the element loses focus after its value was changed, but not commited (e.g., after editing the value of <textarea> or <input type="text">).

(强调我的。- Source

input 活动可能更符合您的喜好:

The input event fires when the value of an <input>, <select>, or <textarea> element has been changed.

[...]

Note: The input event is fired every time the value of the element changes. This is unlike the change event, which only fires when the value is committed, such as by pressing the enter key, selecting a value from a list of options, and the like.

(Source)

这是另一个使用 input 和 CSS 来简化更改的示例。

$(function() {
  $('body').on('input', '.input_w', function() {
    if ($(this).val().length > 1) {
      $(".save_w").addClass("active");
    } else {
      $(".save_w").removeClass("active");
    }
  });
});
.save_w {
  color: gray;
  pointer-events: none;
}

.save_w.active {
  color: black;
  pointer-events: auto;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="input_w" type="text">

<i class="save_w far fa-save"></i>

将活动 change 更改为 input 即可。

$('body').on('input', '.input_w', function() {
  console.log("change");

  $(".save_w").css("pointer-events", "auto");
  $(".save_w").attr("color", "grey");
});