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

时间:2019-05-10 14:14:10

标签: javascript input selection

存在带有一些文本的输入。输入聚焦时(第一次单击输入),必须选择此输入中的所有文本;第二次单击输入时,必须选择特定的单词。

我尝试实现与Chrome(版本74.0.3729.131(正式内部版本)(64位))中的URL栏相同的功能。

您当前可以看到的输入行为: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');
    }

1 个答案:

答案 0 :(得分:0)

onfocus事件处理程序总是在ondblclick之前执行。 我建议延迟焦点处理程序,以便可以在可能的双击后执行(更新了小提琴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">