3

我有方形 DIV 和大型纵向和横向图像。

我需要将图像放入一个 DIV 中,并带有额外的部分overflow:hidden

例如。如果纵向设置宽度=div的宽度高度:自动

与风景相反。

我试过这个脚本,但它没有工作;

        $('.magic').each(function(){
        if($(this).css('width')>$(this).css('height')){
            $(this).css('height', '300px');
            $(this).css('width', 'auto');                
        }
        else{
            $(this).css('width', '300px');
            $(this).css('height', 'auto');


        }
    });

PS 图片不能拉伸,必须缩放

4

3 回答 3

5

使用一些像这样的 CSS

.magic.portrait {
    height: 300px;
    width: auto;
}

.magic.landscape {
    width: 300px;
    height: auto;
}

只需用你的 JS 添加一个类

$('.magic').each(function(){
    if($(this).width() > $(this).height()){
        $(this).addClass('landscape');
    }else{
        $(this).addClass('portrait');
    }
});

这也有助于保持您的应用程序逻辑和样式很好地分开。更好的是,在服务器端添加这些类,并完全避免使用 JavaScript。

于 2013-03-12T02:11:01.757 回答
1

如果您真的想要一个 javascript/jquery 解决方案,请查看jQuery AnyStretch插件。它只是做你想做的事。

于 2013-03-12T02:19:25.860 回答
0

如果事先知道图像大小,则可以使用 CSS 完成所有这些操作。

如果您决定必须使用 javascript,那么当前代码的问题是$(this).css('width')检索字符串"300px",而不是数字,因此两个字符串的比较无法正常工作,就像您期望数字比较工作一样。

您可以将其转换为数字,也可以只使用$(this).width()它返回以像素为单位的数字。

工作示例:

$('.magic').each(function(){
    var self = $(this);
    var width = self.width();
    var height = self.height();
    if (width > height) {
        self.css({height: "300px", width: "auto"});
    } else {
        self.css({width: "300px", height: "auto"});
    }
});

演示:http: //jsfiddle.net/jfriend00/B7hVp/

于 2013-03-12T02:02:20.783 回答