开发者

How to detect whether user selected entire document or not in HTML and JavaScript?

I'm developing a off-line web-page for iPhone Safari.

For highlighting the user's selection in web-page. I've implemented following code.

function highlight() {

    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt) {
            range =开发者_JAVA百科 sel.getRangeAt(0);
        }
        document.designMode = "on";
        if (range) {
            sel.removeAllRanges();
            sel.addRange(range);
        }        
        document.execCommand("HiliteColor", false, "yellow");       
        document.designMode = "off";
    }
}

That's working perfectly for normal selection.

Edit :

How to detect has user selected entire document or not?

What to do?


The following is a function that will return a Boolean indicating whether all of the contents of the specified element are selected and works in all major browsers, including IE. You can use this with document.body to test whether the whole page is selected.

function areElementContentsSelected(el) {
    var range, elRange;
    if (window.getSelection && document.createRange) {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            elRange = document.createRange();
            elRange.selectNodeContents(el);
            for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                range = sel.getRangeAt(i);
                if (range.compareBoundaryPoints(range.START_TO_START, elRange) <= 0 && range.compareBoundaryPoints(range.END_TO_END, elRange) >= 0) {
                    return true;
                }
            }
        }
    } else if (document.selection && document.selection.createRange && document.selection.type == "Text") {
        range = document.selection.createRange();
        elRange = range.duplicate();
        elRange.moveToElementText(el);
        return range.compareEndPoints("StartToStart", elRange) <= 0 && range.compareEndPoints("EndToEnd", elRange) >= 0;
    }
    return false;
}

alert( areElementContentsSelected(document.body) );


But I don't want to allow user to select entire document & highlight it.

Why not?

Interfering with users' typically-expected-browsing-experience is never a good thing and usually leads to frustrated users simply disabling JS or choosing to abandon your site altogether.

Please reconsider.


Could you use selectNodeContents(document body) (pseudocode) to create a range representing the whole page, and then compare that to the range that the user selected?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜