【问题标题】:resize all images if width > something jquery如果宽度 > 某些 jquery,则调整所有图像的大小
【发布时间】:2012-10-01 22:38:03
【问题描述】:

如果宽度>,我想调整页面中所有图像的大小,例如 400px

我试试这段代码

 var img_width =  $("#my_img").width();
//alert(img_width)
if(img_width > 380){
 $("#my_img").width('380');
}

但没有任何效果,并且在页面上我有超过 10 张图片 ti 有 id my_img

img 标签

img src='tttttt.jpg' id="my_img"

我如何调整它的大小?

因为我有一个模板,我不希望 img 的宽度超过 400px

【问题讨论】:

  • 有多个具有相同id 的项目是无效的html。请改用classes。

标签: jquery resize


【解决方案1】:

你不能为此使用 CSS 吗?

max-width:400px;

就像代达罗斯所说,在一个文档中多次使用相同的 id 是无效的 html。

【讨论】:

  • 如果这解决了您的问题,请不要忘记接受此答案作为已接受的答案。
【解决方案2】:
<script>
    jQuery(document).ready(function(){
        jQuery(".my_img").each(function(e){
            if(e.width()>380){
                jQuery(this).attr('width','380');
            }
        });
    });
</script>

【讨论】:

    【解决方案3】:

    首先,具有相同id 的多个项目是无效的html。正如我在上面的评论中所说,请改用class

    假设您的 html 如下所示:

    <img class="my_img" src="someurl" style="width: 390px;" />
    <img class="my_img" src="someurl" style="width: 390px;" />
    <img class="my_img" src="someurl" style="width: 390px;" />
    <img class="my_img" src="someurl" style="width: 340px;" />
    

    以下 jquery 将调整前三个图像的大小,前提是它们符合相应的规则:

    $(document).ready(function() {
        $('.my_img').each(function(index,value) {
            if ($(value).width() > 380) {
                $(this).css('width', 380);
            }
        });
    });​
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-29
      • 1970-01-01
      • 2013-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-25
      相关资源
      最近更新 更多