通过分辨率使用Jquery更改宽度和高度

时间:2013-03-04 04:50:00

标签: jquery image responsive-design

我在这里发布了一个新问题,当我的屏幕分辨率低于980px时,我得到了如何删除图像宽度和高度的答案。

我收到了这段代码:

<img width="477" height="299" src="/uploads/2012/01/415.jpg" class="attachment-portfolio2 wp-post-image"/> 

var images;

$(function() {  
    images = $('img.wp-post-image');
    removeSize();
});

$(window).resize(removeResize);

function removeSize()
{
    if($(window).width() < 980 && images.length > 0)
    {
        images.removeAttr('width').removeAttr('height');
    }
}

现在,我想将其更改为“更改宽度jquery命令”,并尝试了:

 var images;

    $(function() {  
        images = $('img.wp-post-image');
        removeSize();
    });

    $(window).resize(removeResize);

    function removeSize()
    {
      if ( $(window).width() < 960) {
    $('img.wp-post-image').animate({width:'400px'});
    $('img.wp-post-image').animate({height:'300px'});
}
else {
    $('img.wp-post-image').animate({width:'400px'});
    $('img.wp-post-image').animate({height:'300px'});
}
    }

但是不行,有什么不对?谢谢

1 个答案:

答案 0 :(得分:1)

如果您将其简化为常规功能,您将获得:

$(function () {
    var images = $('img.wp-post-image');
    $(window).on('resize', function() {
        if ($(window).width() < 960) {
            $('img.wp-post-image').animate({ width: '400px' });
            $('img.wp-post-image').animate({ height: '300px' });
        } else {
            $('img.wp-post-image').animate({ width: '400px' });
            $('img.wp-post-image').animate({ height: '300px' });
        }
    });
});

除了if / else似乎是静音的事实之外,它可以正常工作,因为无论如何都会做同样的事情,并且你同时为同一个元素制作两次动画?您是否尝试链接动画,如果是这样,请使用回调功能:

$('img.wp-post-image').animate({ width: '400px' }, 500, function() {
      $(this).animate({ height: '300px' }, 500);
});
相关问题