如何在Javascript中获取所选文本的坐标?
答案 0 :(得分:1)
由于Sarfraz的链接主要指文本框,我认为你想获得任何选择的位置,这里是获得它的步骤:
offset
方法在这里很有用。简而言之,我不会开始实现代码,因为IE有一种代码和其他类型的浏览器很棘手。
请注意,此方法仅对文本选择可靠地工作,如果您选择以图像开头,则可能会遇到困难。
答案 1 :(得分:0)
OnMouseDown()和OnMouseUp()事件是否有用?
要选择您需要单击鼠标按钮的文本..并完成选择,您可以执行mouseUp ..
使用OnMouseDown事件,您可以获得首字母的坐标,并使用OnMouseUp获取最后一个字母..
<head>
<script type="text/javascript">
function show_coords(event)
{
x=event.clientX;
y=event.clientY;
document.getElementById("one").innerHTML='X coords: ' + x + ', Y coords: ' + y;
}
function show_coords2(event)
{
x=event.clientX;
y=event.clientY;
var newb= document.getElementById("one").innerHTML+'<br/>'+'X coords: ' + x + ', Y coords: ' + y;
document.getElementById("one").innerHTML=newb;
}
</script>
</head>
<body onMouseDown="show_coords(event)" onMouseUp="show_coords2(event)">
<p>Click in the document to see the co-ordinates of the selected text</p>
<p id="one"></p>
</body>
Click in the document. An alert box will alert the x and y coordinates of the mouse pointer.
X coords: 8, Y coords: 15
X coords: 555, Y coords: 17
mouseDown没有问题..但是在mouseUp上,两个坐标都取决于你触发事件的光标的确切位置..这就是为什么你可以在上面的例子中看到co-ord Y的微小变化..
请提供反馈意见写作评论..
希望它有所帮助: - )