document.elementFromPoint
을 사용하면 마우스를 움직이는 요소를 찾을 수 있습니다. 마우스 움직임 기록을 업데이트하는 이벤트 핸들러 만 있으면됩니다.
var pointer = {x: 0, y: 0};
window.addEventListener("mousemove",function(e) {
pointer.x = e.clientX;
pointer.y = e.clientY;
});
function getTextAtPointer() {
return document.elementFromPoint(pointer.x,pointer.y).textContent;
}
유일한 문제는 사용자가 어떤 단어를 가리키게하는지 알려주지 않는다는 것입니다. 내가 생각할 수있는 유일한 해결책은 텍스트 콘텐츠를 구문 분석하고 span
태그의 모든 단어를 랩핑 한 다음 document.elementFromPoint
을 다시 호출하여 span
의 특정 단어를 얻는 것입니다. 이 작업을 수행하는 것은 무리한 작업 인 것처럼 들리므로이 문제에 대한 더 쉬운 방법이 있습니다.
편집
나는 span
태그 모든 단어를 교체하는 방법을 시도하기로 결정했습니다, 나는 그것을 테스트 할 때, 그렇게, 어떤 인식 할 수있는 방법으로 성능에 영향을 미칠 것 같지 않았다 부담없이 사용해보십시오. 다음은 업데이트 된 getTextAtPointer
기능입니다.
function getTextAtPointer() {
var elem = document.elementFromPoint(pointer.x,pointer.y);
for(var i=elem.childNodes.length-1; i>=0; i--) {
var node = elem.childNodes[i];
if(node.nodeType==3) {
var words = node.textContent.split(/\s+/);
if(words.length>1) {
var frag = document.createDocumentFragment();
for(var j=0; j<words.length; j++) {
if(words[j].length>0) {
var span = document.createElement("span");
span.textContent = words[j];
frag.appendChild(span);
if(j!=words.length-1) {
frag.appendChild(document.createTextNode(" "));
}
}
}
elem.replaceChild(frag,node);
}
}
}
var word = document.elementFromPoint(pointer.x,pointer.y).textContent;
if(word.search(/\s+/)!=-1) {
return "";
}
return word;
}