【问题标题】:javascript image resize doesn't work in ie8javascript图像调整大小在ie8中不起作用
【发布时间】:2011-03-03 21:39:04
【问题描述】:

我公司的新网页布局依赖于 150 像素宽的图像。以前的设计要求图像高度为 125 像素。因此,所有图像都根据它们的宽度/高度比具有不同的宽度。我把一些 javascript 放在一起来调整图像大小以适应他们的空间,直到我们的实习生开始在 Photoshop 中调整图像大小。我的临时解决方案似乎在除 ie8 之外的所有东西(包括 ie6 的所有东西)中都能正常工作!这是代码。

$('div.item > div.left > a > img').load(function(){
    var img = $(this);
    img.each(function(){
        var width = img.width();
        var height = 125;
        var ratio = width/height;
        if(width > 150){
            var newWidth = 150;
            var newHeight = newWidth/ratio;
            img.attr({width:newWidth, height:newHeight});
        }
    });
});

任何想法都非常感谢

【问题讨论】:

  • 不确定这是否对您有帮助,但有时我在未指定“px”时遇到问题

标签: javascript jquery


【解决方案1】:

有时图像会被浏览器 chached 并且加载事件不会被调用。在这种情况下,尝试更改“每个”事件的图像大小。 Chrome 和浏览器 IE > 9 可以缓存适当大小的图像,但 IE

将以下内容添加到您的页面:

<!--[if lt IE 9]>
<script type="text/javascript">
    $('div.item > div.left > a > img').each(function(){
    var img = $(this);
    img.each(function(){
    var`enter code here` width = img.width();
    var height = 125;
    var ratio = width/height;
    if(width > 150){
        var newWidth = 150;
        var newHeight = newWidth/ratio;
        img.attr({width:newWidth, height:newHeight});
    }
   });
});
</script>
<![endif]-->

【讨论】:

    【解决方案2】:

    改变

    img.attr({width:newWidth, height:newHeight});

    img.css({width:newWidth+'px', height:newHeight+'px'});

    它应该如你所愿。

    【讨论】:

      【解决方案3】:

      您应该尝试处理图像对象本身

      $('div.item > div.left > a > img').load(function(){
      var img = $(this)[0];
      img.each(function(){
          var width = img.width();
          var height = img.height();
          var ratio = width/height;
          if(width > 150){
              var newWidth = 150;
              var newHeight = newWidth/ratio;
              img.width(newWidth);
              img.height(newHeight));
          }
       });
      });
      

      【讨论】:

      • var img = $(this)[0]; 抛出错误。 '对象不支持此操作' 代码:0。有什么想法吗?
      【解决方案4】:

      我也遇到了同样的问题。

      我用这个解决了:

      $(window).load(function() {
      ....
      });
      

      它似乎在我的网站上工作。

      【讨论】:

        猜你喜欢
        • 2012-12-11
        • 1970-01-01
        • 1970-01-01
        • 2014-05-13
        • 2014-08-29
        • 2014-05-12
        • 1970-01-01
        • 2016-12-31
        • 1970-01-01
        相关资源
        最近更新 更多