在绝对位置设置从A到B的选择范围 [英] Set a selection range from A to B in absolute position
问题描述
如何从A(x1,y1)到B(x2,y2)以编程方式选择?
How can I select programmatically from A(x1,y1) to B(x2,y2) ?
x1,y1,x2,y2是像素坐标。我搜索了很多,在我找到的所有函数中,我们必须指定一个特定的标签然后选择它的内容。
x1, y1, x2, y2 are pixel coordinates. I searched a lot and in all functions I found, we had to specify a specific tag and then it selects its content.
推荐答案
您可以在所有浏览器的当前版本中执行此操作。这些浏览器至少具有以下一项:
You can do this in current versions of all browsers. These browsers have at least one of the following:
- 基于标准的方法,由Firefox> = 20实现,来自CSSOM View规范:
document.caretPositionFromPoint()
- WebKit的专有版本:
document.caretRangeFromPoint()
。 - IE的专有
TextRange
对象,其中包含moveToPoint()
获取像素坐标的方法。但是,似乎在所有版本的IE中使用的moveToPoint()
可能是错误的(参见此处和此处,例如);我很幸运能够使用我用过的所有文件。
- The standards-based approach, implemented by Firefox >= 20, from the CSSOM View spec:
document.caretPositionFromPoint()
- WebKit's proprietary version of the same:
document.caretRangeFromPoint()
. - IE's proprietary
TextRange
object, which has amoveToPoint()
method that takes pixel coordinates. However, it seems thatmoveToPoint()
, which is used in all version of IE, can be buggy (see here and here, for example); I've simply been lucky that has worked in all the documents I've used it in.
但是,Mozilla确实如此还没有实现任何这些,Opera也没有实现,所以这些浏览器还没有完成。
Firefox 20及更高版本支持 document.caretPositionFromPoint()
。 Opera 15支持 document.caretRangeFromPoint()
Firefox 20 and later supports document.caretPositionFromPoint()
. Opera 15 supports document.caretRangeFromPoint()
以下是一些示例代码。它适用于IE 5 +,WebKit从2010年左右开始,Firefox> = 20,Opera> = 15。
Here's some example code. It works in IE 5+, WebKit from around 2010 onwards, Firefox >= 20 and Opera >= 15.
现场演示: http://jsfiddle.net/timdown/ABjQP/
代码:
function createSelectionFromPoint(startX, startY, endX, endY) {
var doc = document;
var start, end, range = null;
if (typeof doc.caretPositionFromPoint != "undefined") {
start = doc.caretPositionFromPoint(startX, startY);
end = doc.caretPositionFromPoint(endX, endY);
range = doc.createRange();
range.setStart(start.offsetNode, start.offset);
range.setEnd(end.offsetNode, end.offset);
} else if (typeof doc.caretRangeFromPoint != "undefined") {
start = doc.caretRangeFromPoint(startX, startY);
end = doc.caretRangeFromPoint(endX, endY);
range = doc.createRange();
range.setStart(start.startContainer, start.startOffset);
range.setEnd(end.startContainer, end.startOffset);
}
if (range !== null && typeof window.getSelection != "undefined") {
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (typeof doc.body.createTextRange != "undefined") {
range = doc.body.createTextRange();
range.moveToPoint(startX, startY);
var endRange = range.duplicate();
endRange.moveToPoint(endX, endY);
range.setEndPoint("EndToEnd", endRange);
range.select();
}
}
这篇关于在绝对位置设置从A到B的选择范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!