开发者

Strange firefox/javascript behavior using ranges

Hey, so I'm working with ranges, I'm trying to limit the selection an user can make on the page. What I mean 开发者_运维百科is the user can select whatever he wants, but the selection cannot exceeds the boundaries I will set.

First I define the "boundaries" with a defined range. Then I compare the current user selection with the defined range, if the current selection start is below the boundaries OR the current selection end is above the boundaries I adjust accordingly so the user selection never exceeds the defined boundaries range/selection.

The function below only works If I output an alert before the process starts, If I remove the alert, then firefox behaves weird (Like selecting another part of the page, etc.)

The question is: Why the following code works with an alert and why it doesn't work as expected without the alert?

Thanks!

var range = document.createRange(); // this is the boundaries range
range.selectNodeContents(document.getElementById("container"));

function test(){
            alert("let's go"); // if I remove this alert, the code doesn't work as expected, WHY?!
            if(window.getSelection().rangeCount == 0){
                return;
            }
            var curRange = window.getSelection().getRangeAt(0);
            if(curRange.compareBoundaryPoints(Range.START_TO_START, range) < 0){
                curRange.setStart(range.startContainer,range.startOffset);
            }

           if(curRange.compareBoundaryPoints(Range.END_TO_END, range) > 0){
               curRange.setEnd(range.endContainer,range.endOffset);
            }
        }


Firstly, to work in other browsers (except IE <= 8, which has a totally different way of doing this stuff) you'll need to reselect the range. Secondly, to make it work in Firefox, you need to work on a clone of the original selected range:

function test(){
    var sel = window.getSelection();
    if (sel.rangeCount == 0) {
        return;
    }
    var curRange = sel.getRangeAt(0).cloneRange();
    if (curRange.compareBoundaryPoints(Range.START_TO_START, range) < 0) {
        curRange.setStart(range.startContainer,range.startOffset);
    }
    if (curRange.compareBoundaryPoints(Range.END_TO_END, range) > 0) {
        curRange.setEnd(range.endContainer,range.endOffset);
    }
    sel.removeAllRanges();
    sel.addRange(curRange);
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜