简体   繁体   中英

How to get the bounding box of a wrapping inline element with prototype

I used to use cumulativeOffset() and getDimensions() to calculate the bounding box of elements, but just realized that cumulativeOffset returns the top left corner oft the start of an element. Meaning: if an inline element wraps, and the next line is more to the left than the start, I get a displaced bounding box.

After researching a bit, I found that I can use getClientRects() to get all rects. I could then go through, and just take the left position of the rect that's most to the left.

I was wondering if there is a better way of doing this... I just didn't find a boundingBox() prototype function. Did I overlook it?

Edit: I also just found out that getClientRects() is not supported by all browser, so this is no solution.

I don't see a boundingBox() function either, but I wonder if using the same technique ( cumulativeOffset() and getDimensions() ) on the parent via: getOffsetParent() would do what you want. getOffSetParent() :

"Returns element's closest positioned ancestor. If none is found, the body element is returned."

Which should account for word-wrapping where the second line is further left.

I've never heard of a way to do this. You could set it position:relative, drop a 1x1 absolutely positioned div into it, position it right:0, get that div's LEFT + WIDTH, and subtract the offset width of the original inline item from that value.

Saying that, total hack, maybe you need to rethink the reason you want to do this!

The solution given by dfitzhenry seems not working in the case of multiline inline elements. Here's my Javascript solution : get your inline element nextSibling, check if it is an inline element, otherwise create a new inline element, add it to your inline element's parent and then get its offsetLeft:

 var parentContainer = inline_elm.parentNode;
 var nextsib = inline_elm.nextSibling;
 var remove_next_sibling = false;
 if(!nextsib || nextsib.clientWidth != 0){
     remove_next_sibling = true;
     var temp= document.createElement('span');
     parentContainer.insertBefore(temp, nextsib);
     nextsib = temp;
 }

 var inline_bounding_right = nextsib.offsetLeft;
 if(remove_next_sibling)    parentContainer.removeChild(nextsib);

This is an old post, but the standard method now to get a bounding box is getBoundingClientRect() , which is supported in all major browsers and has had at least partial support since 2009 in most browsers. Enjoy!

PS getClientRects() is also very useful for getting the individual bounding boxes of the wrapped text. It seems to have the same browser support as getBoundingClientRect() , since the one depends on the other, and this source suggests that it's well supported.

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