如果div使用百分比本身,则从jquery获取div宽度和高度

时间:2017-06-04 19:25:17

标签: jquery html

我需要在px中获得div大小,而它本身设置为100%作为width&高度。

但CDT输出给出: 宽度= 437像素,高度= 439 但是当我尝试检查div标签CDT显示 width = 420和height = 422px 时(如图所示)

为什么在我使用

时会发生这种情况
var divWidth = $('.divhandler').width();
var divHeight = $('.divhandler').height();

enter image description here

  function getImageDimensions(path, callback) {
    var img = new Image();
    img.onload = function() {
      callback({
        width: img.width,
        height: img.height
      });
    }
    img.src = path;
  }
  var imgWidth;
  var imgHeight;

  function DoReset(_width, _height) {
    imgWidth = _width;
    imgHeight = _height;
    console.log("IMG Width:" + imgWidth);
    console.log("IMG Height:" + imgHeight);
    //get div 
    var divWidth = $('.divhandler').width();
    var divHeight = $('.divhandler').height();
    console.log("DIV Width:" + divWidth);
    console.log("DIV Height:" + divHeight);
    var ratioCalc;
    var newImageHeight;
    var newImageWidth;
    if (imgWidth > imgHeight) {
      if (divWidth > imgWidth) {
        ratioCalc = imgWidth / imgHeight;
        newImageHeight = divHeight * ratioCalc;
        newImageWidth = (imgWidth / imgHeight) * newImageHeight;
        $('.imghandler').css('width', newImageHeight + 'px');
        console.log("1");
      } else {
        ratioCalc = imgHeight / imgWidth;
        newImageHeight = divWidth * ratioCalc;
        $('.imghandler').css('height', newImageHeight + 'px');
        console.log("2");
      }
    } else {
      console.log("2");
    }
  }
  getImageDimensions("http://www.dailymobile.net/wp-content/uploads/wallpapers/landscape-wallpapers-320x240/landscape-wallpapers-320x240-03.jpg", function(data) {
    imgWidth = data.width;
    imgHeight = data.height;
    DoReset(data.width, data.height);
  });
  $(window).resize(function() {
    getImageDimensions("cgihandle.jpg", function(data) {
      imgWidth = data.width;
      imgHeight = data.height;
      DoReset(imgWidth, imgHeight);
    });
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="divhandler" style="width:100%;height:100%;background:#ccc"> <img src="http://www.dailymobile.net/wp-content/uploads/wallpapers/landscape-wallpapers-320x240/landscape-wallpapers-320x240-03.jpg" class="imghandler" /> </div>

2 个答案:

答案 0 :(得分:0)

在鼠标悬停期间,将在CDT中显示div的总大小,以及图像中显示的填充和边框。你的实际div大小是437x439,但增加的原因是它周围的填充。enter image description here

答案 1 :(得分:0)

.height().width()不要包含边框,填充和边距。如果您想要宽度计算中包含的那些,请使用.outerHeight().outerWidth()

http://api.jquery.com/outerheight/

http://api.jquery.com/outerwidth/