开发者

Detect Visible Width of Div

开发者 https://www.devze.com 2023-03-12 21:39 出处:网络
This is a general programming question (it doesn\'t have a specific purpose/application yet). If I create a tag in HTML (lets say an img, a, or div), but don\'t de开发者_Python百科fine its width or u

This is a general programming question (it doesn't have a specific purpose/application yet).

If I create a tag in HTML (lets say an img, a, or div), but don't de开发者_Python百科fine its width or use a percent width (ie width:50%) how would I go about finding the actual width it is displaying (in pixels) using javascript? I would also perfer for it to be crossbrowser, but that isn't my major concern.

I mean I know that if it is a block element like div it will take 100%, but how do I find what 100% is? Do I just have to climb the node tree until I find a parent node with a defined width and then calculate it based on that?

I am aware of clientWidth and clientHeight, but neither of those are crossbrowser or w3 approved...


Check out the .width() function in jQuery's API. This is definitely cross-browser and returns the width in pixels (see documentation for details).


A possible solution would be to use a prototype method

Element.prototype.getElementWidth = function() {
    if (typeof this.clip !== "undefined") {
          return this.clip.width;
    } else {
      if (this.style.pixelWidth) {
          return this.style.pixelWidth;
      } else {
             return this.offsetWidth;
      }
    }
};
0

精彩评论

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