如何判断文本输入字段dom节点是否*没有*使用javascript进行选择? [英] How can I tell if a text input field dom node does *not* have a selection with javascript?

查看:126
本文介绍了如何判断文本输入字段dom节点是否*没有*使用javascript进行选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我检查inputFieldDomNode.selectionStart时,它总是返回一些数字,即使它没有文本选择并且其中也没有插入符号.那么,如何确定没有是否具有文本选择呢?

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?

推荐答案

好吧,我知道了:

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
    }
}

基本上,当您有活动的文本输入时,其父元素是range.startContainer,因此不仅要检查它是否是range.startContaine的子元素,还要确保其正确range.startOffset确定的child(选定的孩子).另外,您还必须确保输入是所选的 only ,因为输入可能包含在较大的选择中.

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.

注意:我认为在唯一选择实际输入节点而不是其内容的情况下,这可能仍然会失败.这是一种极为罕见的边缘情况,我不确定是否可以通过用户输入(甚至可能通过dom API来实现).

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).

这篇关于如何判断文本输入字段dom节点是否*没有*使用javascript进行选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆