我想知道是否有办法通过提供屏幕坐标(x,y)来选择HTML中的单个单词。基本上我想要一个自定义的window.getSelection,但不是由光标(或触摸)触发,而是(x,y)点将是输入。感谢。
答案 0 :(得分:0)
一个 BASIC 解决方案可能是这样的:
(单词的检测基于一个空格'严格地说)!
仅用于演示目的,编码和非字母字符超出范围!
var $j = function(val, space) {return JSON.stringify(val, '', space || '');};
var $l = function(val) {document.body.insertAdjacentHTML('beforeend', '<div><pre>' + val + '</pre></div>')};
$lj = function(val, space) {$l($j(val, space));};
function getWordAtPosition(x,y){
var caretPosition = document.caretPositionFromPoint( x , y );
var str = caretPosition.offsetNode.data;
var len = caretPosition.offsetNode.length;
var pos = caretPosition.offset;
var result = {
function: 'getWordAtPosition( ' + x + ' , ' + y + ')' ,
x : x ,
y : y ,
data : str ,
startAt : pos ,
endAt : pos ,
curChar : str[pos] ,
};
if(!result.curChar) return result;
if( result.curChar === " ") return result;
while(pos>=0 && str[pos]!==' ') pos--;
result.startAt = pos+1;
var endAt = str.indexOf(' ' , result.startAt);
endAt = endAt === -1 || endAt === result.startAt ? len-1 : endAt-1;
result.endAt = endAt;
result.word = str.substring(result.startAt , result.endAt+1);
$lj( result , ' ');
}
document.onclick = function(evt) {
getWordAtPosition(evt.clientX, evt.clientY);
};
&#13;
Click anywhere in this document.
<div>
<p>Testing my code here</p>
</div>
&#13;