簡體   English   中英

如果選擇任何內容,如何確定(跨瀏覽器)?

[英]How to determine (cross-browser) if anything is selected?

如何確定(跨瀏覽器)是否選擇了任何內容(在當前文本字段中)? 我只需要一個truefalse 我找到了jQuery.selection但它的使用超載了。

window.getSelection().toString()應該適合你 - 所有瀏覽器和IE7 +都支持

編輯:我很驚訝這對輸入元素不起作用。 但是, https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement中提到了selectionStartselectionEnd屬性,因此您可以使用它們。

console.log(!!(el.selectionStart - el.selectionEnd));
// where el = your input element, like el = $('input')[0]

雖然有一個小故障,我發現如果在選擇文本后模糊輸入,這些值不會改變,所以我將使用querySelector來查找輸入元素是否具有焦點:

document.querySelector('#input:focus') //returns first matched element or null

最簡單,最可靠(我猜)是從jQuery.selection插件中獲取代碼。 您只需要此功能:

    var _getCaretInfo = function(element){
    var res = {
        text: '',
        start: 0,
        end: 0
    };

    if (!element.value) {
        /* 値がない、もしくは空文字列 */
        return res;
    }

    try {
        if (win.getSelection) {
            /* IE 以外 */
            res.start = element.selectionStart;
            res.end = element.selectionEnd;
            res.text = element.value.slice(res.start, res.end);
        } else if (doc.selection) {
            /* for IE */
            element.focus();

            var range = doc.selection.createRange(),
                range2 = doc.body.createTextRange(),
                tmpLength;

            res.text = range.text;

            try {
                range2.moveToElementText(element);
                range2.setEndPoint('StartToStart', range);
            } catch (e) {
                range2 = element.createTextRange();
                range2.setEndPoint('StartToStart', range);
            }

            res.start = element.value.length - range2.text.length;
            res.end = res.start + range.text.length;
        }
    } catch (e) {
        /* あきらめる */
    }

    return res;
};

如果IE8 <支持不需要 - if (doc.selection) { section可以刪除。

要從此函數獲取布爾值,只需替換return res; return !!res.text;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM