大家好。
我有一个 div,其背景图像的大小设置为 cover
。
如何使用 javascript 或 jquery 获取背景大小?
我的意思是,背景将用其尺寸(宽度或高度)之一填充 div,我想了解完整(计算的)图像的宽度和高度,而不仅仅是可见部分。
<style>
body {width:100%; height:100%}
#fullCoverBg {background-image:url("ani_bg.jpg"); background-repeat:no-repeat; background-size:cover; background-position:right;}
@media all and (max-width : 1000px) {
/* small screens */
aside {height:30%; width:100%;}
#fullCoverBg {height:70%; width:100%;}
}
@media all and (min-width : 1001px) {
/* big screens */
aside {height:100%; width:30%;float:left;}
#fullCoverBg {height:100%;width:70%;float:left;}
}
</style>
<body>
<aside>this div stay on head on small devices, and go on the left side on big screens </aside>
<div id="fullCoverBg"></div>
</body>
假设我们调整 wwindow 的大小,我们将看到背景覆盖整个 div,当然有些部分将不可见,因为“覆盖”填充了 div 的宽度或高度...对于每次调整大小,整个图像的尺寸(可见部分和不可见部分)是多少?
最佳答案
您需要预加载图像。
var background = new Image();
background.src = "your-image.jpg";
var bgHeight = background.height;
var bgWidth = background.width;
好吧,这就是真正的答案。这需要一些思考,并从这个答案中借用了一些代码:How can I determine the background image URL of a div via JavaScript?
但是,我终于明白了。我看到您想要一个 jQuery 答案,但我只在 Native、JS 中工作,对于断开连接感到抱歉。
编辑:我发现了一些缺失的逻辑,所以我把它放进去了。现在应该可以了,希望如此。
http://jsfiddle.net/TLQrL/2/ - 反射(reflect)新逻辑的新链接
var div = document.getElementById("myDiv");
var style = div.currentStyle || window.getComputedStyle(div, false);
var bg = style.backgroundImage.slice(4, -1);
var background = new Image();
background.src = bg;
background.onload = function() {
if (background.width > background.height) {
var ratio = background.height / background.width;
if (div.offsetWidth > div.offsetHeight) {
var bgW = div.offsetWidth;
var bgH = Math.round(div.offsetWidth * ratio);
if (bgH < div.offsetHeight) {
bgH = div.offsetHeight;
bgW = Math.round(bgH / ratio);
}
} else {
var bgW = Math.round(div.offsetHeight / ratio);
var bgH = div.offsetHeight;
}
} else {
var ratio = background.width / background.height;
if (div.offsetHeight > div.offsetWidth) {
var bgH = div.offsetHeight;
var bgW = Math.round(div.offsetHeight * ratio);
if (bgW > div.offsetWidth) {
bgW = div.offsetWidth;
bgH = Math.round(bgW / ratio);
}
} else {
var bgW = Math.round(div.offsetWidth / ratio);
var bgH = div.offsetWidth;
}
}
console.log(bgW + ", " + bgH);
}
关于jquery - 检索设置为 "cover"的背景图像的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23518501/