使用范围的奇怪的 firefox/javascript 行为
嘿,所以我正在使用范围,我试图限制用户可以在页面上进行的选择。我的意思是用户可以选择他想要的任何内容,但选择不能超出我将设置的界限。
首先,我用定义的范围定义“边界”。然后,我将当前用户选择与定义的范围进行比较,如果当前选择开始低于边界或当前选择结束高于边界,我会相应调整,以便用户选择永远不会超出定义的边界范围/选择。
下面的函数仅适用于如果我在进程开始之前输出警报,如果我删除警报,则 Firefox 的行为会很奇怪(例如选择页面的另一部分等)。
问题是:为什么以下代码适用于警报并且为什么在没有警报的情况下它不能按预期工作?
谢谢!
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);
}
}
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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,要在其他浏览器中工作(IE <= 8 除外,它的处理方式完全不同),您需要重新选择范围。其次,要使其在 Firefox 中工作,您需要对原始选定范围进行克隆:
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: