如何使用JavaScript获取光标下的单词?如果我有<p> some long text </p>在我的HTML页面上,我如何知道鼠标的光标就在‘text’这个词的上方?
3 回答
森林海
TA贡献2011条经验 获得超2个赞
function getWordAtPoint(elem, x, y) { if(elem.nodeType == elem.TEXT_NODE) { var range = elem.ownerDocument.createRange(); range.selectNodeContents(elem); var currentPos = 0; var endPos = range.endOffset; while(currentPos+1 < endPos) { range.setStart(elem, currentPos); range.setEnd(elem, currentPos+1); if(range.getBoundingClientRect().left <= x && range.getBoundingClientRect().right >= x && range.getBoundingClientRect().top <= y && range.getBoundingClientRect().bottom >= y) { range.expand("word"); var ret = range.toString(); range.detach(); return(ret); } currentPos += 1; } } else { for(var i = 0; i < elem.childNodes.length; i++) { var range = elem.childNodes[i].ownerDocument.createRange(); range.selectNodeContents(elem.childNodes[i]); if(range.getBoundingClientRect().left <= x && range.getBoundingClientRect().right >= x && range.getBoundingClientRect().top <= y && range.getBoundingClientRect().bottom >= y) { range.detach(); return(getWordAtPoint(elem.childNodes[i], x, y)); } else { range.detach(); } } } return(null);}
getWordAtPoint(e.target, e.x, e.y);
添加回答
举报
0/150
提交
取消