简体   繁体   中英

Display width of containing DIV

I'm setting up a sort of "debugging" page with a number of unique DIVs with different proportional widths (set in percentages).
I'd like each div to contain text that will display the containing div's width in pixels, responding live to resizing of the viewport.

I'm a relative new to jQuery and have found myself able to display an element's width using:

$('.show_width').html($(this).width());​​

But, I'm clearly doing something wrong because this only works once - not on every unique div. Further, I'd like to add something like "Width: ___px" to each div.

Any help is much appreciated. Thanks.

you need to use $.each to loop through the elements

 $(document).ready(function () {
     getWidths();
     $(window).resize(function() {
         getWidths();            
     });

     function getWidths() {
         $('.show_width').each(function() {
           $(this).html("");
           $(this).html($(this).html() + "<br />Width: " + $(this).width() + "px");
        });
     }
  });​

If i get it, use resize event callback function:

  $(window).resize(function(){
         $('.show_width').each(function() {
             $(this).html($(this).width()+' * '+$(this).height());​
          }​
    });

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