javascript - 为什么我们不能将函数绑定(bind)到 :disabled input fields?

标签 javascript jquery html css

当我尝试将 JavaScript/jQuery .hover.click 函数绑定(bind)到 时:disabled input 字段,没有任何函数被触发。

请参阅下面的代码段。

$(document).ready(function() {
  var button_1 = $("#button_1");
  
  button_1.hover( function() {
    console.log("Hover event button 1");
  });
  button_1.click( function() {
    console.log("Click event button 1");
  });
});

function button_2_click() {
  console.log("Click even button 3");
}
function button_2_hover() {
  console.log("Hover even button 3");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p>Hover over one of the buttons, and you'll see none of the console messages gets logged. When removing the `disabled` property, all events are fired.</p>
<button id="button_1" disabled>Disabled 1</button>
<button id="button_2" onmouseover="button_2_hover();" onclick="button_2_click();" disabled>Disabled 2</button>

MDN 关于 disabled 属性的说明如下:

Indicates whether the element is disabled or not. If this attribute is set to true the element is disabled. Disabled elements are usually drawn with grayed-out text. If the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire.

我试图实现的是,当用户 :hover 悬停在 button:disabled 上时,将显示一条消息。

我知道我可以为此使用 title="text"。然而,事实并非如此。我在右上角使用了一个带有消息的小弹出窗口。消息存储在 javascript 对象 中。

我的问题:
我该如何解决这个问题?还是无法将 .hover()onmousemove 函数绑定(bind)到 disabled input 字段?

最佳答案

click 部分是 per specification :

A form control that is disabled must prevent any click events that are queued on the user interaction task source from being dispatched on the element.

您正在测试的用户代理似乎更进一步并且还阻止了与悬停相关的事件(例如,Chrome 和 IE 似乎可以)。其他用户代理可能不会(例如,Firefox 允许与悬停相关的事件。)

如果您想要这些事件,您可以让按钮保持启用状态,然后将它们设置为看起来已禁用,并防止单击它们执行它们本来可以执行的操作,尽管这可能会造成困惑的用户体验。

或者,您可以在 button 中放置一个 span,并在其上挂接事件:

$(document).ready(function() {
  var button_1 = $("#button_1 span");
  
  button_1.hover( function() {
    console.log("Hover event button 1");
  });
  button_1.click( function() {
    console.log("Click event button 1");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p>Hover over one of the buttons, and you'll see none of the console messages gets logged. When removing the `disabled` property, all events are fired.</p>
<button id="button_1" disabled><span>Disabled 1</span></button>

按钮的某些部分不会触发事件(周围的位),但您可能可以使用 CSS 修复该问题...

关于javascript - 为什么我们不能将函数绑定(bind)到 :disabled input fields?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43495838/

相关文章:

javascript - 使用本地硬盘时将 iframe 加载到 div

javascript - 在 DataTables jquery 插件中设置复选框值

html - 无法在 div 旁边添加文本

javascript - 如何使用 jquery 更改标签文本

javascript - 使用 Spring MVC 访问 Javascript 中的模型属性

javascript - 关于使用 css 打印 a4 尺寸

javascript - 如何从命令行运行 Node.js 程序而无需字 'node'

javascript - mysql 结果在 javascript 全局数组中

javascript - 如何使用 animate.css 在 barba js 中设置过渡持续时间

javascript - 当另一个 div 到达页面顶部时简单的 CSS 更改