本文介绍了从点获取DOM文本节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 就像我可以从 document.elementFromPoint 或 document.getElementFromPoint 中得到一个元素,是吗如果点在文本节点,可能以某种方式获取文本节点?我猜,如果至少我可以得到文本节点的位置和大小,我可以找出它们中的哪一个包含的点。但是DOM节点没有位置属性。是否可以这样做?Just like I can get an element from a point with document.elementFromPoint or document.getElementFromPoint, is it possible to somehow get a text node if the point is at a text node? I guess if at least I could get the text node's position and size I could then figure out which of them contains the point. But then DOM nodes don't have position properties. Is it possible to do this at all?推荐答案这是一个在所有当前浏览器中可用的实现: https://github.com/nuxodin/q1/blob/master/q1。 dom.jsHere is an implementation that works in all current browsers:https://github.com/nuxodin/q1/blob/master/q1.dom.jsdocument.betaNodeFromPoint = function(x, y){ var el = document.elementFromPoint(x, y); var nodes = el.childNodes; for ( var i = 0, n; n = nodes[i++];) { if (n.nodeType === 3) { var r = document.createRange(); r.selectNode(n); var rects = r.getClientRects(); for ( var j = 0, rect; rect = rects[j++];) { if (x > rect.left && x < rect.right && y > rect.top && y < rect.bottom) { return n; } } } } return el;}; 这篇关于从点获取DOM文本节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-23 01:11
查看更多