javascript:查找锚定链接的绝对大小

发布于 2024-08-17 23:04:29 字数 1509 浏览 2 评论 0原文

我需要计算页面中每个锚定链接的位置、高度和宽度。我知道如何找到 x,y 坐标,但高度和宽度有问题。当链接内部有子项(图像、div 等)时,就会出现问题,因此 heightOffset 和 widthOffset 将不起作用。有没有办法做到这一点而不需要对所有孩子进行计算并计算他们的大小?

编辑:

这里有一些代码来演示我的意思(每当按下鼠标时都会调用按下函数):

function findPos(obj) {
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
    }
    return [curleft,curtop];
}

function getHeight(elem) {

          if (elem.style.pixelHeight) {
             return elem.style.pixelHeight;
          } else {
             return elem.offsetHeight;
          }
    }
function getWidth(elem) {

    if (elem.style.pixelWidth) {
       return elem.style.pixelWidth;
    } else {
       return elem.offsetWidth;
    }
}

function press(e)
{


      x= e.pageX;
      y= e.pageY;

    window.alert(x+","+y);


            var links = document.getElementsByTagName('a');
            for (i = 0; i < links.length; i++){
                var pos = findPos(links[i]);
                window.alert(x+","+y+" "+pos[0]+" " + pos[1] + " "+links[i].offsetWidth+ " "+links[i].offsetHeight);
                if (x >= pos[0] && x <= pos[0] + getWidth(links[i]) && y >= pos[1] && y <= pos[1] + getHeight(links[i])){
                    window.alert(links[i].href);
                    i = links.length;
                }
            }


}

例如,当我遇到带有图像的链接时,它不会返回正确的尺寸。

谢谢

I need to calculate the position, height and width of every anchored link in my page. I know how to find the x,y coords, but I have a problem with the height and width. The problem appears when the link has children inside (images, divs etc), so heightOffset and widthOffset won't work. Is there a way to do this without going on all the children and calculating their sizes?

EDIT:

Here is some code to demonstrate what I mean (the press function is called whenever the mouse is being pressed):

function findPos(obj) {
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
    }
    return [curleft,curtop];
}

function getHeight(elem) {

          if (elem.style.pixelHeight) {
             return elem.style.pixelHeight;
          } else {
             return elem.offsetHeight;
          }
    }
function getWidth(elem) {

    if (elem.style.pixelWidth) {
       return elem.style.pixelWidth;
    } else {
       return elem.offsetWidth;
    }
}

function press(e)
{


      x= e.pageX;
      y= e.pageY;

    window.alert(x+","+y);


            var links = document.getElementsByTagName('a');
            for (i = 0; i < links.length; i++){
                var pos = findPos(links[i]);
                window.alert(x+","+y+" "+pos[0]+" " + pos[1] + " "+links[i].offsetWidth+ " "+links[i].offsetHeight);
                if (x >= pos[0] && x <= pos[0] + getWidth(links[i]) && y >= pos[1] && y <= pos[1] + getHeight(links[i])){
                    window.alert(links[i].href);
                    i = links.length;
                }
            }


}

When I encounter a link with an image for instance it doesn't return me the right size.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

北笙凉宸 2024-08-24 23:04:29

offsetWidth/Height 对包含图像的链接做了很多工作,只要您没有做任何奇怪的事情,例如溢出或定位图像或其他子内容,以便它们超出了其父级的内容范围。

您的代码在 IE 上没有使用 offsetHeight,而是使用 pixelHeight,它的作用与您可能认为的不同。坚持使用offsetHeight。

相反,您使用的是 event.pageX/Y,这是 IE 没有的非标准扩展。遗憾的是,从事件中获取页面相对坐标的唯一可靠方法是使用 clientX/Y 并针对视口滚动进行调整。

我真的不知道为什么您要努力枚举链接位置,而对于鼠标单击/按下事件,您可以非常可靠地使用 event.target/srcElement。事实上,这是唯一可靠的方法。考虑一个分成两行文本的链接。现在你得到的是一个非矩形区域;您无法使用简单的 x 和 y 范围测试来测试特定鼠标位置是否位于该区域内。

offsetWidth/Height do very much work on links that contain images, as long as you haven't done anything weird like overflowing or positioning the images or other child content so that they fall out of the content area of their parent.

Your code isn't using offsetHeight on IE, it's using pixelHeight, which doesn't do what perhaps you think it does. Stick with offsetHeight.

Conversely, you are using event.pageX/Y, which is a non-standard extension IE doesn't have. Sadly the only reliable way to get page-relative co-ordinates from an event is to use clientX/Y and adjust for viewport scrolling.

I don't really know why you are going to the effort of enumerating link positions when for a mouse click/down event you can quite reliably get the element that was clicked on using event.target/srcElement. In fact this is the only reliable way to do it. Consider a link that has split over two text lines. Now what you've got is a non-rectangular region; you can't test whether a particular mouse position lies within that area using a simple x and y range test.

っ〆星空下的拥抱 2024-08-24 23:04:29

正确的属性是 offsetHeight(不是 heightOffset)和 offsetWidth(不是 widthOffset)。
这些属性应该正确返回您想要的大小,因为假设溢出设置为可见,子级将扩展元素以适应。在任何情况下都无需计算子级的大小。

offsetHeightoffsetWidth 不属于任何标准,但大多数浏览器似乎都实现了它们。

由于您在使用 Safari 和 offsetHeight 时遇到问题,也许您可​​以尝试 getClientRects() 方法:

http://www.quirksmode.org/dom/tests/rectangles.html

var dims   = links[i].getClientRects()[0];
var width  = dims.right - dims.left;
var height = dims.bottom - dims.top;

但是不能说我曾经使用过 getClientRects() 。听起来结果可能更接近 clientWidth 和 clientHeight。

进一步编辑
我想出了一个解决方法。以下内容不起作用:

<a href="#">
  <img onclick="press(event);" src="http://sstatic.net/so/img/logo.png" alt="" />
  <!-- onclick handler alerts with size 250x15 -->
</a>

但是将 标签包裹在 标签周围,如下所示:

<a href="#"><span>
  <img onclick="press(event);" src="http://sstatic.net/so/img/logo.png" />
  <!-- onclick handler alerts with size 250x61 -->
</span></a>

解决了问题。至少,它在 Chrome 中是这样的,但就像我之前说过的,Chrome 和 Safari 共享 WebKit 渲染引擎,所以它也应该适用于 Safari。

The correct properties are offsetHeight (not heightOffset) and offsetWidth (not widthOffset).
Those properties should correctly return the sizes you're after, because the children would expand the elements to fit, assuming overflow is set to visible. There's no need to calculate the sizes of the children in any situation.

offsetHeight and offsetWidth aren't part of any standard but most browsers seem to have them implemented anyway.

Since you're having problems with Safari and offsetHeight, maybe you could try the getClientRects() method:

http://www.quirksmode.org/dom/tests/rectangles.html

var dims   = links[i].getClientRects()[0];
var width  = dims.right - dims.left;
var height = dims.bottom - dims.top;

Can't say I've ever used getClientRects(), however. It sounds like the results may be closer to clientWidth and clientHeight.

FURTHER EDIT
I figured out a workaround. The following does not work:

<a href="#">
  <img onclick="press(event);" src="http://sstatic.net/so/img/logo.png" alt="" />
  <!-- onclick handler alerts with size 250x15 -->
</a>

But wrapping a <span> tag around the <img> tag, like so:

<a href="#"><span>
  <img onclick="press(event);" src="http://sstatic.net/so/img/logo.png" />
  <!-- onclick handler alerts with size 250x61 -->
</span></a>

Fixes the problem. At least, it does in Chrome but like I said before Chrome and Safari share the WebKit rendering engine, so it should work for Safari too.

成熟稳重的好男人 2024-08-24 23:04:29

您不应使用 elem.style.* 中的值来确定元素的大小。这些值是 CSS 样式,并不可靠。仅使用 offsetWidthoffsetHeight

要获取元素的位置,请使用此问题的答案:检索HTML 元素的位置 (X,Y)

You should not use the values in elem.style.* to determine the size of an element. These values are CSS styles and aren't reliable. Use only offsetWidth and offsetHeight.

To get the position of an element, use the answers to this question: Retrieve the position (X,Y) of an HTML element

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文