gpt4 book ai didi

javascript - 在html中选择屏幕坐标(x,y)处的单个单词

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:34:36 26 4
gpt4 key购买 nike

我想知道是否有一种方法可以通过提供屏幕坐标 (x,y) 在 HTML 中选择单个单词。基本上我想要一个自定义的 window.getSelection,但不是由光标(或触摸)触发,而是输入一个 (x, y) 点。谢谢。

最佳答案

一个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);

};
Click anywhere in this document.
<div>
<p>Testing my code here</p>
</div>

关于javascript - 在html中选择屏幕坐标(x,y)处的单个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33552960/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com