javascript - 防止 mousedown 窃取当前输入的焦点,但允许选择文本

标签 javascript jquery

是否可以防止 div 中的鼠标按下来窃取焦点,但允许在此容器中选择文本(例如 <div> )?

/*// Version #1: Focus kept, but text is not selectable
$('div').on('mousedown', function(event) {
  event.preventDefault();
});
/**/

// Version #2: Focus kept, text selectable, but focus is missing for a short time (flickering when css is applied to focused state)
$('div').on('mousedown', function(event) {
  window.setTimeout(
    function() {
      $('input').focus();
    }, 1
  );
});
/**/

$('input').focus();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" />
<div>A div container with some text, that should be selectable but not stealing focus of the input field</div>

当我点击文本时,我的第二个版本会闪烁(在当前的 Chrome 中测试)。在 Firefox 中,选择始终从输入字段开始。有没有更好的解决办法?

最佳答案

答案就在你眼前:)

/*// Version #1: Focus kept, but text is not selectable
$('div').on('mousedown', function(event) {
  event.preventDefault();
});
/**/

// Version #2: Focus kept, text selectable, but focus is missing for a short time (flickering when css is applied to focused state)
$('input').on('focusout', function(event) {
 //setTimeout(function(){$('input').focus()}, 1);
});
/**/


//$('div').on('mouseup', function(event) {
//  $('input').focus();
//});

$('html').on('mouseup', function(event) {
  $('input').focus();
});


$('input').focus();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" />
<div>A div container with some text, that should be selectable but not stealing focus of the input field</div>

如果您的 mouseup 发生在该 div 之外,则焦点丢失的问题将持续存在。

另一种方法是即使在 html 上也绑定(bind) mouseup,尽管这在我看来有点过分,但似乎可行。

问题是,如果您希望焦点返回到输入复选框,则需要使用 focusout 事件,如代码段中所示。另一种“保持”焦点在输入框上的范例行不通,因为 Javascript 是同步的,一次只能运行一件事。

关于javascript - 防止 mousedown 窃取当前输入的焦点,但允许选择文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39295465/

相关文章:

javascript - 使用 Switch/Toggle Css/javascript 更改文本颜色

javascript - 在 Blogger 中的相同标签下导航下一篇和上一篇文章

javascript - 分组并存储 html 'data' 属性

javascript - 如何在div标签中做多行标题?

javascript - 选择兄弟 div jquery 的跨度

jquery - MVC : Need to pass an list or array of strings from controller to view

javascript - 为当前图像/幻灯片分配类别

javascript - 使用 TweenMax 在 PixiJS 中进行缩放

jquery - 如何使用 jQuery 滚动到 Kendo 网格中的选定行?

jquery - 从 div 内容中仅删除 <br/>