我需要在px中獲取div大小,而本身它設置爲100%寬度&高度。從jquery獲取div寬度和高度,如果該div使用百分比本身
但是CDT輸出給出: 寬度= 437px和高度= 439 但是當我嘗試檢查該div標籤CDT顯示寬度= 420和高度= 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>
這是因爲margin和padding你DIV –
的但我在使用CDT的控制檯,然後輸入以下' $('。divhandler')。width();'它會顯示正確的大小 – Elshan