我有一些 div 框,里面有一张图片。我想要它做的是,如果图像高度小于其内部的 div 框,则向图像添加一个类。
但是我已经将图像设置为 div 框的 100% 宽度,所以当我在图像上使用 jquery 的 .Height() 时,它会给我原始大小。有什么建议吗?
<div class="boxe">
<asp:Literal ID="imgProjekt1" runat="server" />
<asp:Literal ID="litProjekt1" runat="server"/>
</div>
<div class="boxe forsideboxMiddle">
<asp:Literal ID="imgProjekt2" runat="server" />
<asp:Literal ID="litProjekt2" runat="server"/>
</div>
带有 ID imgProjekt1 和 ImgProjekt2 的字面量从代码隐藏中创建一个普通的 img 标签。
最佳答案
$(function() {
var myImage = $('img'),
originalHeight = myImage.height();
getImgSize(myImage, originalHeight, myImage[0].src);
});
/* http://stackoverflow.com/questions/1944280/determine-original-size-of-image-cross-browser */
function getImgSize(myImage, currentHeight, imgSrc) {
var newImg = new Image();
newImg.onload = function() {
if(newImg.height > currentHeight) {
myImage.addClass('smaller');
alert(newImg.height + ' > ' + currentHeight);
}
}
newImg.src = imgSrc;
}
编辑:
只有当图像的高度小于其父级 div
时,才应将该类添加到图像中。较大的图像不应获得该类,即使它们小于源图像也是如此。
代码时间:
$(function() {
var myImage = $('img');
getImgSize(myImage);
});
/* http://stackoverflow.com/questions/1944280/determine-original-size-of-image-cross-browser */
function getImgSize(myImage) {
myImage.each(function() {
var that = $(this),
parent = that.parent(),
originalHeight = that.height(),
parentHeight = parent.height(),
newImg = new Image();
newImg.onload = function() {
if(
newImg.height > originalHeight &&
parentHeight > originalHeight
) {
that.addClass('smaller');
}
}
newImg.src = that[0].src;
});
}
关于javascript - 如何获得CSS操作图像的高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24740944/