简体   繁体   中英

How do I calculate the width between two elements?

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>

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)

Thanks

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.

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.

Edit: 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];
}

If you mean the horizontal distance, I would say it's something like:

X position of element 2
minus 
x position of element 1 plus width of element 1

to get the width, use getWidth()

to get the position, positionedOffset() might be the right thing, I'm not 100% sure and it depends on your elements' positioning.

And a general caveat, if your elements have padding , it will depend on the browser (IE / FF) whether the padding is calculated into the width or not. This may also apply to the border. You will have to play around and see.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM