【问题标题】:Jquery image width and heightjquery图片宽高
【发布时间】:2013-12-31 11:25:10
【问题描述】:

如果图像宽度大于高度,我正在尝试将图像的高度设置为 150px,如果图像高度大于宽度,则图像的宽度将更改为 150px。

这是我的标记:

CSS:

       .posts { width:150px; height:150px; }

HTML:

        <div class="posts"><img src="image" /></div>

JQUERY 脚本:

        var photoW = $('.posts img').width();
        var photoH = $('.posts img').height();

        if( photoW > photoH ){
            $(".posts img").css("width", "auto").css("height", "100%");
        }

        else {
            $(".posts img").css("width", "100%").css("height", "auto");
        }

它不起作用,我不知道为什么。如果您能帮助我,我将不胜感激。

【问题讨论】:

  • 你错过了div class="posts"&gt;的结束语
  • 首先你有一个 " 不见了。
  • 我的错,我在复制标记时出错了,对不起!但这不是它不起作用的原因..
  • 您的代码似乎在这里工作:jsfiddle.net/psNZ7 - 您检查控制台是否有任何错误?
  • @Adrift 我在 Tumblr 上做这个,所以也许这就是问题所在......

标签: jquery


【解决方案1】:

问题可能是当你执行时图像可能尚未加载...所以等待图像加载

试试类似的东西

jQuery(function ($) {
    $('.posts img').load(function () {
        if (this.width) {
            if (this.height > this.width) {
                this.style.height = '100%'
            } else {
                this.style.width = '100%'
            }
        }
    }).filter(function () {
        return this.complete
    }).trigger('load')
})

演示:Fiddle

【讨论】:

  • 还是不行,但那是因为 tumblr,谢谢回复!
【解决方案2】:

这里是fiddle 给你,你应该在准备好的文档上运行代码

$(document).ready(function(){
var photoW = $('.posts img').width();
        var photoH = $('.posts img').height();

        if( photoW > photoH ){
            $(".posts img").css({width: "auto",height: "100%"});
        }

        else {
            $(".posts img").css({width: "auto",height: "100%"});
        }
});

【讨论】:

    【解决方案3】:

    无意冒犯,但我不确定您的意图是什么。一个典型的实例要求是在图像周围维护一个特定的边界框,比如 150 像素。 Here is a fiddle 就是这样做的。请注意,宽度和高度没有 CSS,因为它们都是动态设置的。这是代码:

    var $photo, w_px, h_px;
    
    $photo = $('.posts img');
    w_px = $photo.width();
    h_px = $photo.height();
    
    if ( h_px > w_px && h_px > 150 ) {
      $photo.css({ height : 150, width : '' });
    }
    else if ( w_px > 150 ) {
      $photo.css({ height : '', width : 150 });
    }
    

    如果您的要求与您键入时一样,则不是this fiddle should do the trick

    【讨论】:

    • 我的目的是让图像始终保持正方形,但我不想将宽度和高度设置为 150 像素,因为它们看起来很糟糕。我将帖子的溢出设置为隐藏,所以如果图像的宽度大于高度,高度将设置为 150px,并且由于隐藏的溢出,宽度的剩余部分将不会显示。如果高度大于宽度,则相同。帖子宽度更改为 150 像素,剩余高度将不会显示。你明白我的意思吗?
    • 当然,这很有意义。然后你应该设置第二个小提琴,因为这正是你正在寻找的。唯一缺少的是隐藏溢出的容器。顺便说一句,一个方便的方法是使用背景图像和背景大小,位置为“中心,中心”
    • 那个小提琴仍然不起作用,我不知道为什么,我找到了一个很好且简单的解决方案:“.posts img { min-width: 100%; min-height: 100%;宽度:自动;高度:自动;}"。这正是我想要的。无论如何,感谢您的 cmets!
    • 这确实是一个聪明的解决方案,它避免了所有的 JavaScript。非常好。它在 x-browser 上的表现如何?
    • 我在 Firefox、Chrome、IE 和 Safari 上对其进行了测试,它在所有设备上都能完美运行 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-24
    • 2012-12-30
    • 2022-12-06
    • 1970-01-01
    • 1970-01-01
    • 2018-06-09
    • 1970-01-01
    相关资源
    最近更新 更多