javascript - 单击元素时聚焦输入字段,除非容器内的某些文本突出显示

标签 javascript jquery mouseevent jquery-events

点击容器元素#text时,输入字段#chatInput需要获得焦点,除非该元素内的文本(通过双击或鼠标突出显示)选择)

// what I got so far which is incomplete
$('#text').on('click', function (e) {
  $('#chatInput').focus();
});

fiddle :https://jsfiddle.net/xhykmtwy/4/

最佳答案

您可能需要考虑以下解决方案,该解决方案检查单击事件后是否在 text 元素中选择了某些文本:

$('#text').click(function () {
    var container = this;
    setTimeout(function () {
        var selectedElement = null;
        var selectedText = null;
        if (window.getSelection) {
            // For modern browsers
            var selection = window.getSelection();
            if (selection) {
                selectedText = selection.toString();
                if (selection.anchorNode) {
                    selectedElement = selection.anchorNode.parentNode;
                }
            }
        }
        else if (document.selection && document.selection.type === "Text") {
            // For IE < 9
            var selection = document.selection;
            selectedText = selection.createRange().text;
        }
        if (!(selectedText && selectedText.length > 0) || (selectedElement !== container && !$(container).has(selectedElement))) {
            setTimeout(function () { $('#chatInput').focus(); }, 0);
        }
    }, 0);
});

根据我的测试,它可以在 IE(包括 IE7)、Firefox 和 Chrome 中运行。唯一的异常(exception)是在 IE 中双击,它不会选择文本。你可以在这个jsfiddle中看到结果.

setTimeout 的调用可确保所有选择处理均已完成,尤其是在单击所选文本以取消选择它时。

鸣谢:

  1. 我使用了Eineki在How can I get the element in which highlighted text is in?中提出的方法检查 text 元素是否包含所选文本。

  2. 在 IE < 9 中处理选择的代码可以在 Tim Down 对帖子 Get the Highlighted/Selected text 的回答中找到。 .

关于javascript - 单击元素时聚焦输入字段,除非容器内的某些文本突出显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39436439/

相关文章:

javascript - 在所有图像加载无效后执行js

jquery - 避免使用 JQuery 同时显示 2 个项目

jquery - 检查用户是否滚动到屏幕的特定百分比

java - 使用 mouseClicked() 时拖动的鼠标坐标也被计算在内?

java - 没有 javac 编译器错误,但 mouseEntered 方法不起作用

javascript - Firestore .orderBy() 也可以返回文档而不查询字段

javascript - 在html文件中编写脚本的正确方法

python - 没有 MousePress 的 PyQt4 MouseMove 事件

javascript - 为什么在明确定义的情况下得到 'toUpperCase' 的未定义?

JavaScript 子菜单不持久