我有一些元素。页面上的数量不断变化,请记住这一点。
该元素称为 .portalimg。我需要说明一下,如果 width > height
,请将其 width
设置为 125px。如果 height > width
,请将 height
设置为 125px。
这是我所拥有的:
$('.portalimg').each(function() {
var pimgw = $(this).width();
var pimgh = $(this).height();
if (pimgw > pimgh) {
$(this).css('width','125px')
} else {
$(this).css('height','125px')
}
});
编辑:它提醒成功但不应用 width
和 height
。
我哪里出错了?
编辑 2:从下面使用最干净的代码更新了代码。这仍然只限制了 height 属性,即使图像比宽高。看一看:
http://jacksongariety.com/gundoglabs/
编辑 3:问题是它们都返回 0。如果我有一个警报说 pimgw 或 pimgh 的值,它总是 0。
编辑 4:最终获得了最好的、最干净的缓存代码,它总是会正确加载,即使它从缓存中绘制图像也是如此:
$(function(){
$('.portalimg').ready(function(){
$('.portalimg').fadeTo(0,1).each(function(index) {
var a = $(this);
if (img.width() > a.height()) {
a.css('width','135px')
} else {
a.css('height','125px')
}
});
});
});
最佳答案
如果类 portalimg 有多个元素,您可以简单地使用 .each 迭代器:http://api.jquery.com/each/
$(function() {
$('.portalimg').each(function(index) {
var img = $(this);
if (img.width() > img.height()) {
img.css('width','125px')
} else {
img.css('height','125px')
}
});
}
关于javascript - 我怎么能用 jQuery 说 "if width > height"然后 "do this"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9578414/