开发者

Can't calculate width of elements

开发者 https://www.devze.com 2023-01-02 03:55 出处:网络
I try to get width of DOM objects: function resizeArea(){ var width = 0; area.children().each(function(i){

I try to get width of DOM objects:

    function resizeArea(){
      var width = 0;
      area.children().each(function(i){
          alert(this.offsetWidth);
          width += this.offsetWidth;
      });
      area.css('width', width);
    }

In get results:

开发者_JAVA百科
  1. Chrome: 800
  2. Opera: 708
  3. FF: 783
  4. IE: 714

But if see it in firebug, dragonfly and other debuggers i see correct 908px. I don't know where porblem. I run this fun after domloaded.

Here is HTML and css of block:

<div class="scroll_area" id="scroll">
   <div class="area" id="area">
      <div class="category">
      [..]
      </div>
   </div>
 </div>
 <style>
    #scroll {
        position:realtive; width: 800px, heght: 400px;
   }
   #area {
        position:absolute; left: 0; top: 0;
   }
   #area .category, #area .category .text, #area .category .image{
       width: 200px
   }
 </style>

And that interesting. This function later work correctly, only at first run, for first calculating.


I managed to get this to work (with jQuery): Please let me know if I misunderstood the question

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <style type="text/css">
    #scroll {
        position:realtive; width: 800px, heght: 400px;
   }
   #area {
        position:absolute; left: 0; top: 0;
   }
   #area div.category {
       width: 200px;
       display: block;
   }
 </style>
 <script src="http://code.jquery.com/jquery-1.4.2.js" type="text/javascript" language="Javascript"></script>
 <script type="text/javascript">
 function resizeArea(){
      var width = 0;
      jQuery("#area").children().each(function(i){
          alert(this.offsetWidth);
          width += this.offsetWidth;
      });
      jQuery("#area").css('width', width);
    }
 </script>
</head>
<body>
<div class="scroll_area" id="scroll">
   <div class="area" id="area">
      <div class="category">
      [..]FIRST ALERT
      </div>
      <div class="category">
      [..]SECOND ALERT
      </div>
   </div>
 </div>
 <script type="text/javascript">resizeArea();</script>

 <br /><br /><br /><a href="javascript:void(0);" onClick="resizeArea()">Fun Function Again</a>
</body>
</html>
0

精彩评论

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