如何让按钮不要聚焦?

Mik*_*eat 22 javascript extjs focus button

我希望我的(ExtJS)工具栏按钮在单击时不会抓住网页上的焦点,而是在点击时保持焦点不变的情况下执行"事物".我怎么做?

rea*_*l4x 34

取消默认行为onmousedown可防止元素获得焦点:

// Prevent capturing focus by the button.
$('button').on('mousedown', 
    /** @param {!jQuery.Event} event */ 
    function(event) {
        event.preventDefault();
    }
);
Run Code Online (Sandbox Code Playgroud)


Als*_*nde 6

document.activeElement存储当前聚焦的元素.

因此,在工具栏上,您可以为此函数添加"mousedown"处理程序:

function preventFocus() {
  var ae = document.activeElement;
  setTimeout(function() { ae.focus() }, 1);
}
Run Code Online (Sandbox Code Playgroud)

试试这个例子:

<html>
<head>
<script>
function preventFocus() {
  var ae = document.activeElement;
    setTimeout(function() { ae.focus() }, 1);
}
</script>
</head>
<body>
<input type="text"/>
<input type="button" onmousedown="preventFocus()" onclick="alert('clicked')" value="Toolbar" />
</body>
</html>
Run Code Online (Sandbox Code Playgroud)


Luk*_*ger 5

这通常对我有用:

<button 
  tabindex="-1"
  onclick="javascript:console.log('do your thing')"
>My Button</button>
Run Code Online (Sandbox Code Playgroud)

来自https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex

值(通常tabindex="-1")的装置,该元件应是可聚焦的,但不应该是通过顺序键盘导航可达。使用 JavaScript 创建可访问的小部件最有用。


小智 5

投票最高的答案在技术上是正确的,但取决于 jQuery...

这是一个更简单的例子:

<span onclick="document.execCommand('bold', false);" onmousedown="event.preventDefault();"></span>
Run Code Online (Sandbox Code Playgroud)