如何用JavaScript区分网页中的空白区域和非空白区域?空白区域包括:
- 未被 DOM 元素占用的区域。
- DOM 元素的边距、边框和填充。
编辑:
作为对第一条评论的回应:我正在开发一个基于网络的电子书阅读器。空白区域的光标设置为 {cursor:move},以便用户可以拖动和滚动网页。
最佳答案
您可以递归地遍历每个元素并附加 onmouseover
和onmouseout
每个包含文本的事件(前者启用 text
光标,后者启用 move
光标),例如:
function attachEvents(e) {
if (n.nodeType == 3) { // Node.TEXT_NODE
// A text node - add the parent as an element to select text in
e.parentNode.onmouseover = elmMouseOver /* define your own event fns */
e.parentNode.onmouseout = elmMouseOut
}
else if (n.nodeType == 1) { // Node.ELEMENT_NODE
for (var m=e.firstChild; m != null; m = m.nextSibling) {
attachEvents(m)
}
}
}
我能想到的确保鼠标悬停实际上是“文本”而不是空白区域的最佳方法是使用例如<div><span>content</span></div>
并输入 mouseover
/mouseout
事件在 <span>
这样空白区域就不会触发事件。如果可以的话,我建议您这样做,因为根据我的经验,如果您使用带填充的 block 元素,事情可能会变得非常复杂。例如:
| The quick brown fox jumps |
| over the lazy dog | <- onmouseover/out of SPANs will ignore the space
after "dog" while DIVs won't and you won't need
to calculate padding/margins/positions which
makes it faster and more simple to implement
如果您必须使用 block DIV:您可以使用类似 jQuery 的 jSizes
的东西。插件以像素为单位获取边距/填充或 this (获取继承的 CSS 值并通过从末尾删除 px
部分等来解析自己)
之后,您可以使用 position()
计算出位置在 jQuery 中。我个人不使用 jQuery 来做我的事情,但我使用那些特定的“查找位置”功能,并发现它们是我认为最好的功能之一,这在很大程度上是因为测试它们的用户数量。
祝你好运!
关于javascript - 如何用JavaScript区分网页中的空白区域和非空白区域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2933867/