简体   繁体   English

javascript图像调整大小在ie8中不起作用

[英]javascript image resize doesn't work in ie8

My company's new web layout depends on an image being 150px wide. 我公司的新Web布局取决于150px宽的图像。 The previous design required the images to be 125px tall. 先前的设计要求图像高度为125px。 So all the images have different widths based on their width/height ratio. 因此,所有图像都基于其宽高比而具有不同的宽度。 I put some javascript together to resize the images to fit in their space until our interns get around to sizing the images in photoshop. 我将一些javascript放在一起以调整图像大小以适合其空间,直到我们的实习生开始在Photoshop中调整图像大小。 My temporary solution seems to work fine in everything but ie8, including ie6 of all things! 我的临时解决方案似乎在除ie8之外的所有事物上都能正常工作,包括所有事物的ie6! Here's the code. 这是代码。

$('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});
        }
    });
});

Any thoughts are greatly appreciated 任何想法都将不胜感激

Sometimes the images are chached by browser and load event is not called. 有时,浏览器会打乱图像,并且不会调用load事件。 Try changing image sizes on 'each' event in that case. 在这种情况下,请尝试在“每个”事件上更改图像大小。 Chrome and browsers IE > 9 can cache images with proper sizes but IE <= 8 can't do that. Chrome和浏览器IE> 9可以缓存具有适当大小的图像,但是IE <= 8则不能。 So I included conditional resizing of images for IE <= 8. 因此,我为IE <= 8包括了图像的条件大小调整。

Add the following to your page: 将以下内容添加到您的页面:

<!--[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]-->

Change 更改

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

to

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

and it should work as you wish. 它应该可以按照您的意愿工作。

You should try to work on the image object itself 您应该尝试处理图像对象本身

$('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));
    }
 });
});

I've had the same problem. 我遇到了同样的问题。

I solved it with this : 我用这个解决了:

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

It seems working in my web site. 似乎在我的网站上工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM