如何计算两个元素之间的宽度? [英] How do I calculate the width between two elements?

查看:50
本文介绍了如何计算两个元素之间的宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要计算两个元素之间的宽度,但我不知道该怎么做.假设我有以下内容:

I need to calculate the width between two elements but I'm not sure how I would go about this. Say I have the following:

<ul id="foo">
    <li style="width:10px;"><a href="#">1</a></li>
    <li style="width:20px;"><a href="#">2</a></li>
    <li style="width:30px;"><a href="#">3</a></li>
</ul>

如何计算 1 和 3 之间的距离(答案为 20 像素)?宽度可以像列表项的数量一样可变吗?(我使用的是 Prototype 框架)

How would I calculate the distance between 1 and 3 (answer being 20px)? The width can be variable as can the number of list items? (I'm using the Prototype framework)

谢谢

推荐答案

如果你指的是两个元素之间的水平距离,你需要左边元素的右上角坐标和右边元素的左上角坐标之间的差值.元素的右上角坐标只是左上角坐标加上其宽度,如 Pekka 的回答中给出的那样.

If you mean the horizontal distance between two elements, you need the difference between the top right coord of the left element and the top left coord of the right element. The top right coord of an element is just the top left coord plus its width, as given in Pekka's answer.

要获取元素的左上角位置,可以使用 javascript 方法 offsetLeft().这将返回元素与其父元素之间 x 维度的偏移量.您迭代 DOM 树,添加连续的 offsetLeft,直到到达文档根目录.结果总和是您的 x 位置.优秀的Quirksmode 向您展示了如何做到这一点.

To get the top left position an element, you can use the javascript method offsetLeft(). This returns the offset in the x dimension between an element and its parent. You iterate up the DOM tree adding successive offsetLeft's until you get to the document root. The resulting sum is your x position. The excellent Quirksmode shows you how to do this.

为了完整起见,我包含了示例 javascript 来查找元素的位置:

for completeness, I include example javascript to find an element's position:

function getNodePosition(node) {     
    var top = left = 0;
    while (node) {      
       if (node.tagName) {
           top = top + node.offsetTop;
           left = left + node.offsetLeft;       
           node = node.offsetParent;
       } else {
           node = node.parentNode;
       }
    } 
    return [top, left];
}

这篇关于如何计算两个元素之间的宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆