我有以下简单的代码来获取背景图像尺寸,但它抓住原始图像的大小,而不是我在div中的缩放。我想在缩放后得到像素尺寸,有没有办法做到这一点?
var actualImage = new Image();
actualImage.src = $("#chBox").css('background-image').replace(/"/g, "").replace(/url\(|\)$/ig, "");
actualImage.onload = function () {
width = this.width;
height = this.height;
}
编辑:
用于缩放背景图像的CSS:
#chBox {
height:100%;
width:100%;
background-repeat:no-repeat;
background-image: url(../content/frog/1.jpg);
background-position: center;
-webkit-background-size: contain; /*for webKit*/
-moz-background-size: contain; /*Mozilla*/
-o-background-size: contain; /*opera*/
background-size: contain; /*generic*/
}
答案 0 :(得分:1)
您需要获取所需图片的$('#someImage').css('width')
和$('#someImage').css('height')
,而不是获取实际图片的尺寸。
编辑:
#someImage img {
width: 100px;
height: auto;
}
<td id="image">
<img id="someImage" src="image.jpg">
<script type="text/javascript">
alert($('#someImage').css('width'));
</script>
</td>
上面的代码会提醒“100px”。当然如果你使用一些jQuery来改变图像的宽度,比如$('#someImage').css('width','300px')
,代码就会更新并警告“300px”
答案 1 :(得分:0)
代码正在做你要告诉它的事情。我不相信有一种方法可以抓住'缩放'尺寸。
答案 2 :(得分:0)
好的,感谢大家的回复,但我想到了一些解决方法。我想在以后的jQuery版本中看到这个功能(抓住缩放的宽度,高度),但是通过一些数学计算,它并没有那么糟糕。 从本质上讲,
// create a fake image and load the original from background-img src
var actualImage = new Image();
actualImage.src = $("#chBox").css('background-image').replace(/"/g,"").replace(/url\(|\)$/ig, "");
actualImage.onload = function() {
// get original values
var origWidth = this.width;
var origHeight = this.height;
var width = 0;
var height = 0;
// need to bump it 140px as it seems the div's left comes from the super-container
var bump = 140;
// if the image is fat rather than tall,
if(origWidth > origHeight){
// set width for description to width of bg-img container
var width = $("#chBox").width();
// set left
$(".description").css("left", bump);
// calculate height and set bottom
height = (width * origHeight) / origWidth;
var blankSpace = $("#chBox").height() - height;
$(".description").css("bottom", (blankSpace/2));
} else {
// if image is tall,
var height = $("#chBox").height();
// calculate width
width = (height * origWidth) / origHeight;
// set left
var setLeft = $("#chBox").width();
$(".description").css("left", (setLeft/2) - 58); //wtf, 58?
// set bottom to 0
$(".description").css("bottom", 0)
}
$(".description").width(width);
}
那里有很多特定于网站的东西,但基本上我运行了一些代数来找到图像的比例。如果它是胖图像而不是高图像,则容器的宽度是缩放宽度。高度等于缩放宽度*原始图像高度除以原始图像宽度。由于某种原因(如果有人可以提供帮助,我将不胜感激)保证金:0 auto;当你改变div宽度时,我的CSS的属性不起作用,所以我不得不手动居中。