如何在jquery中找到类的偏移量,宽度和高度?

时间:2016-02-28 19:28:33

标签: javascript jquery html css

我无法找到div的位置,宽度和高度。 .Swing继承了整个窗口的宽度和高度,.Tree的偏移量不正确。

https://jsfiddle.net/sqdgzbp6/3/

HTML

  <div class="view">
      <div class="Swing">
          <img  id="body" src="http://johnwhitegolf.com/wp-content/uploads/2015/05/swing.jpeg">
      </div>           
      <div class="Tree">              
          <img id="tree" src="http://cdn.v-harness.com/wp-content/uploads/2015/03/tree.png">
      </div>
      <div class="Ground">
          <div class="g"></div>
      </div>     
      <p id="test"> l
      </p>
  </div>

CSS

.view {
  position: absolute;
  height: 100%;
  width: 100%;
  z-index: 1;
  background-color: #ff5;
 }

.Swing {
  position: absolute; 
  z-index: 3; 
  height: 100%;
  width: 100%;
  }
  .Swing #body {    
    position: relative;
    height: auto;
    width: 25%;
    left: 30%; 
    top: 35%;
    }
.Tree {
  position: absolute;
  z-index:2;
  height: 100%;
  width: 100%;
}
#tree {
  position: relative;
  height: auto;
  width: 60%;
  left: 30%;
  top: 20%;
}

.Ground {
  z-index: 1;
  width: 100%;
  height: 100%;
}
.Ground .g {
  background-color: green;
  opacity: .5;
  position: relative;
  top: 50%;
  height: 50%;
  width: 100%;
}

的JavaScript

var w = $(window).width(),
    h = $(window).height(),
    tPos = $(".Tree").offset(),
    sW = $(".Swing").width(),
    sH = $(".Swing").height();  

document.getElementById('test').innerHTML = w + ', ' + h + '. Tree: ' + tPos.top + ', ' + tPos.left + '. Swing width ' + sW + ', height ' + sH;

$(window).resize(function() {
   if($(this).width() != w || $(this).height() != h) {
       w = $(window).width(),
       h = $(window).height(),
       tPos = $(".Tree").offset();
       document.getElementById('test').innerHTML = w + ', ' + h + '. Tree: ' + tPos.top + ', ' + tPos.left;
   }
   else { 
       w = $(window).width(),
       h = $(window).height(),
       tPos = $(".Tree").offset();
       document.getElementById('test').innerHTML = w + ', ' + h + '. Tree: ' + tPos.top + ', ' + tPos.left;
   } 
});

谢谢!

0 个答案:

没有答案