开发者

Calculate area of HTML element on website?

开发者 https://www.devze.com 2023-01-29 04:42 出处:网络
I\'m trying to figure out if it\'s possible to calculate the area of a HTML element on a website? In pixels, as a percentage or whatever.

I'm trying to figure out if it's possible to calculate the area of a HTML element on a website? In pixels, as a percentage or whatever.

My first thoughts have been to make the assumption that the element is 100% in width and height, and then try to retrieve the size through a mapping between the HTML and CSS.

So if there's a width/height attribute in the referenced CSS-file I could possibly say that the body element is covered by a column that takes 25% of the area (everything is based on your screen resolution of course - and I'm still trying to figure out how I'd be able to do this programmatically).

Or whether I should render the website and do my calculations based on an image with the most common screen resolution at the time).

Are there any more possible solutions?

(Currently I'm trying to 开发者_JAVA技巧solve this in Perl, but I suppose any language that's got a library for this purpose would be appreciated to know about!)


EDIT: I need to retrieve the visual area for every single element on a page. For example; if there are elements on top of the <body> element, that covers it visually, I want to exclude that area from the <body>'s and so on. A simple raytracing to find the visible area for every element on a page.


EDIT: Let's say we exclude JavaScript - any other approaches possible?


Personally, I would use jQuery - even if you don't use a library, your best bet will be a JavaScript solution.

var $elt = $('#some-element-id'),
    height = $elt.height(),
    width = $elt.width(),
    area = height * width; // contains the area in px^2

http://api.jquery.com/height and http://api.jquery.com/width


This is such a simple problem I don't think JQuery is necessary if you are not already using it.

Try running this:

<div id="myParent">
   What's up?
   <div id="myDiv">Hello there!</div>
</div>

With

    var myDiv = document.getElementById("myDiv");
    alert(myDiv.offsetHeight);
    alert(myDiv.offsetWidth);

    var myParent = myDiv.parentNode;
    alert(myParent.offsetHeight);
    alert(myParent.offsetWidth);

Divide resulting widths to get % of space the element takes in it's parent, or simply use the absolute pixel values.


I would recommend using jQuery to do it if possible.

alert('Size: ' + $('li').size());

http://api.jquery.com/size/


Would it be feasible to use javascript? If so you can get the width/height with something like this:

document.getElementById(YourElementsId).style.height;
document.getElementById(YourElementsId).style.width;

However this does depening on how the elements are sytled in the first place. Another option would be

document.getElementById(YourElementsId).clientHeight;
document.getElementById(YourElementsId).clientWidth;
0

精彩评论

暂无评论...
验证码 换一张
取 消