gpt4 book ai didi

jquery - jQuery 中背景图像的实际大小

转载 作者:行者123 更新时间:2023-11-28 11:31:23 25 4
gpt4 key购买 nike

我需要知道背景图像的实际大小(以像素为单位)。

<style>
body {
background-image: url(background.jpg);
background-size: contain;
}
</style>

当我看jQuery的时候,我试过

var img = new Image;
img.src = $('body').css('background-image').replace(/url\(\"|\"\)$/ig, "");
var bgImgWidth = img.width;
var bgImgHeight = img.height;

但这给我带来了真实图像的大小,而不是该图像显示时的大小:如果设备的宽度为 320 像素,bgImgWidth 仍然给我真实图像的 800 像素。

有人知道吗?

最佳答案

如果能得到图片的宽和高,那么就可以根据比例得到显示图片的高度。

var img = new Image();
var $el = $('body');
var containHeight = null;
var containWidth = null;
var containImg = {
w: null,
h: null
};
var bkgImgDims = null;

img.src = $el.css('background-image').replace(/url\(\"|\"\)$/ig, "");

var bgImgWidth = img.width;
var bgImgHeight = img.height;

var imgProportionalH = Math.abs(bgImgHeight / bgImgWidth);
var imgProportionalW = Math.abs(bgImgWidth / bgImgHeight);

// Get the proportions of the background contain image
function getElProportions() {
var elW = $el.width();
var elH = $el.height();
var elProportionalH = Math.abs(elH / elW);
var elProportionalW = Math.abs(elW / elH);

// Check to see if the image is less than 100% of the element width
if(elProportionalH < imgProportionalH) {

containImg.h = elH;
containImg.w = Math.abs( elH / imgProportionalH );

} else {

containImg.h = Math.abs( elW / imgProportionalW );
containImg.w = elW;

}

return containImg;
}


$(document).ready(function(){
bkgImgDims = getElProportions();
});

$(window).resize(function(){
bkgImgDims = getElProportions();
});

JSBin Example

关于jquery - jQuery 中背景图像的实际大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35892137/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com