我需要在px中获得div大小,而它本身设置为100%作为width&高度。
但CDT输出给出: 宽度= 437像素,高度= 439 但是当我尝试检查div标签CDT显示 width = 420和height = 422px 时(如图所示)
为什么在我使用
时会发生这种情况var divWidth = $('.divhandler').width();
var divHeight = $('.divhandler').height();
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>
答案 0 :(得分:0)
答案 1 :(得分:0)
.height()
和.width()
不要包含边框,填充和边距。如果您想要宽度计算中包含的那些,请使用.outerHeight()
和.outerWidth()