我怎么能说“;如果宽度>高度“;那么“;这样做"使用jQuery
How can I say "if width > height" then "do this" with jQuery?
我有一些元素。页面上它们的数量不断变化,请记住这一点。
该元素名为.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版:用下面最干净的代码更新了代码。这仍然只限制高度属性,即使图像更高也会更宽。看看:
http://jacksongariety.com/gundoglabs/
第三版:问题是它们都返回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')
}
});
}
$('.portalimg').each(function() {
var pimgw = $(this).width();
var pimgh = $(this).height();
if (pimgw > pimgh) {
$(this).css('width','125px')
} else {
$(this).css('height','125px')
}
});
这个怎么样:
$('.portalimg').each(function() {
(($(this).width() > $(this).height())
&& ($(this).css('width','125px')) )
|| ($(this).css('height','125px'))
});
http://jsfiddle.net/DerekL/Qx4jF/
您的循环错误,应该使用
pimg = $('.portalimg').each( function() {;
alert("success")
var pimgw = $(this).width();
var pimgh = $(this).height();
if (pimgw > pimgh) {
$(this).css('width','125px')
} else {
$(this).css('height','125px')
}
});
这将对文档中类为".portalimg"的所有find对象调用一个函数。
$('.portalimg').each(function() { var
img = $(this),
w = img.width(),
h = img.height(),
toModify = w > h ? 'width' : 'height';
img.css(toModify, '125px');
}
可以试试这个。其他答案都很好。for和body的语法出现错误。你是说#body还是.body?
$(".portalimg").each(function(){
var pimgw = $(this).width(),
pimgh = $(this).height();
if (pimgw > pimgh) {
$(this).css('width','125px')
}else{
$(this).css('height','125px')
}
});
相关文章:
- 页面在我的javascript执行后重新加载,我不希望它这样做
- 如何在将鼠标悬停在提交/锚点上时检查复选框是否已选中,并显示提示用户这样做的警报
- JavaScript 如果数组包含名称,则不要这样做
- 我用脚本创建了一个按钮.我可以通过点击按钮调用其他函数吗?我这样做,但失败了
- Jquery语法;也这样做”;
- 如果我不这样做会发生什么;t在javascript中的变量中分配新的Image
- 如果他们不这样做,就从我的数组中删除东西't没有前缀
- 如何使用“;这个“;在javascript中?这样做的目的是什么
- 如果我不这样做会发生什么;t有页码吗?继续循环帖子..为什么需要分页,对于页脚
- 禁用 ALT+F4,是的,我知道不建议这样做
- 使用默认值定义构造函数.我这样做对吗?
- 我刚刚开始使用 MEAN 堆栈.我试图将我的表单提交数据存储到 mongo 数据库,但我无法这样做
- 为什么不这样做
- Node.JS/Javascript - 将字符串转换为整数正在返回 NaN,而我不希望它这样做
- 在angularjs中拥有$sce或严格上下文转义有什么好处,为什么反应不需要这样做
- 如何分解此代码以减少重复(以及应该这样做)
- 嵌套的 if/else 语句讨论了分配变量.我已经这样做了,但它仍然不起作用
- blur() 无法以编程方式工作 |但在从用户启动时会这样做
- 如果用户来自网站上的上一页,那么这个,否则这样做
- 我怎么能说“;如果宽度>高度“;那么“;这样做"使用jQuery