How can I tell if a text input field dom node does *not* have a selection with javascript?

若如初见. 提交于 2019-12-25 04:49:27

问题


When I check inputFieldDomNode.selectionStart it always returns some number, even if it does not have a text selection and there's no caret in it. So how can I tell if it doesn't have a text selection?


回答1:


At least window-globally, you can use Selection.isCollapsed

window.getSelection().isCollapsed

Despite the compatibility table, I have found it to be working in Chrome, and apparently it's been supported since IE 9 as well.




回答2:


You can check if a element is selected with something like:

document.getElementById("color-red").checked

which will return a boolean.

If that's what you want, check out an example at http://jsfiddle.net/o5t0ow9g/1/




回答3:


I think (but am not 100% sure) that if the element is not the active element for the document, it can't have a text selection. You can test it using document.activeElement:

if (inputFieldDomNode == document.activeElement) {
    // Do stuff with the selection
}

Example: http://jsfiddle.net/hpseuLj3/1/




回答4:


Ok I figured it out:

exports.getSelectionRange = function (element) {
    if(element.nodeName === 'INPUT' || element.nodeName === 'TEXTAREA') {
        var selection = window.getSelection()
        for(var n=0; n<selection.rangeCount; n++) {
            var range = selection.getRangeAt(0)
            if(range.startOffset === range.endOffset && range.startContainer.children[range.startOffset] === element /*|| range.startContainer === element || */) { // I don't think the input or textarea itself will ever be the startContainer
                return [element.selectionStart, element.selectionEnd]
            }
        }
        // else return undefined - the element doesn't have an active caret or active selection (it still may have an inactive selection)
    } else {
        // .. do something else unrelated to this question
    }
}

Basically, when you have an active text input, its parent is the range.startContainer and so you have to not only check that it is a child of range.startContaine but make sure that its the right child (the child that's selected) which is determined by the range.startOffset. Also, you have to make sure that input is the only thing that's selected, because its possible for the input to be included in a larger selection.

Note: I think this might still fail in cases where the actual input node is the only thing selected and not its contents. This is an incredibly rare edge case and i'm not sure if its even possible via user input (tho probably possible via the dom API).



来源:https://stackoverflow.com/questions/28625615/how-can-i-tell-if-a-text-input-field-dom-node-does-not-have-a-selection-with-j

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!