如何在 input.select() 后突出显示输入中双击的单词

How to highlight double-clicked word in input after input.select()

有一个包含一些文本的输入。当输入聚焦时(第一次单击输入)必须选择此输入中的所有文本,并且当第二次单击输入时必须选择特定单词。

我尝试实现与 Chrome(版本 74.0.3729.131(官方构建)(64 位))中的 URL-bar 相同的功能。

您可以在此处查看输入的当前行为:https://jsfiddle.net/deaamod1s/rh5mw0e4/23/

我看到的唯一解决方案是检查是否双击了输入,然后如果没有双击输入 - 做 input.select()

input.onfocus = function(e) {
        let hasValueWhenGotFocused = false;

        if (input.value) {
            hasValueWhenGotFocused = true;
        }
        setTimeout(() => {
            if (hasValueWhenGotFocused && this.className.indexOf("doubleclicked") == -1) {
                    this.select();
            } else {
                this.classList.remove("doubleclicked");
            }
        },400);
  }

    input.ondblclick = function(e){
        this.classList.add('doubleclicked');
    }

onfocus event handler is always executed before the ondblclick。 我建议延迟焦点处理程序,以便它可以在可能的双击后执行(已更新 fiddle here):

input.ondblclick = function (e) {
    // set....
    this.dataset.dblclick = true;
}

input.onfocus = function (e) {
    this.dataset.dblclick = false;
    setTimeout(function (_this) {
        // if not set...
        if (_this.dataset.dblclick == "false") {
            _this.select();
        } else {
            // remove ...
            delete _this.dataset.dblclick;
        }
    }, 200, this);
}
Try to select second word using only two click<br>
<input type="text" id="input" value="sdsas select_me">