1

今天我在尝试操作图像时遇到了一个有趣的 IE8 情况。

我通过更改它们的 url 来替换加载的图像,当它们被加载时,我试图正确地挤压它们并以视口元素为中心(新图像不像它们的前辈那样是方形的)。但是在 IE8 中(还没有测试过 IE7,从同事那里听说过 IE9 - 一切都很好)图像没有缩放,它们只是以原来的大小下降,而我的

img.height(105);
img.css('margin-left', (shift?-shift:0));

被简单地忽略了。这是解决问题的代码。

    $('.people-images img').each(function () {
        var img = $(this);
        var oUrl = img.attr('src');

        oUrl = oUrl.replace(/[SM]Thumb/, 'LThumb');

        img.bind('load', function () {
            var img = $(this);
            if (this.width > this.height) {
                var shift = (this.width / (this.height / 105) - 105) / 2;
                img.height(105);
                img.css('margin-left', (shift?-shift:0));
            }
            else {
                var shift = (this.height / (this.width / 105) - 105) / 2;
                img.width(105);
                img.css('margin-top', (shift?-shift:0));
            }
        });

        img.attr('src', oUrl);
        img.attr('style', null);
        img.parent().attr('style', null);
    });

请寻找我的解决方案的自我答案。

4

1 回答 1

1

问题出在 IE 图像缓存和它处理事件处理程序的方式上。在这一行我自己清除了css img.attr('style', null);。因此,只需将这种样式删除移到顶部即可解决问题。

$('.people-images img').each(function () {
    var img = $(this);
    var oUrl = img.attr('src');

    oUrl = oUrl.replace(/[SM]Thumb/, 'LThumb');
    img.attr('style', null);

    img.bind('load', function () {
        var img = $(this);
        if (this.width > this.height) {
            var shift = (this.width / (this.height / 105) - 105) / 2;
            img.height(105);
            img.css('margin-left', (shift?-shift:0));
        }
        else {
            var shift = (this.height / (this.width / 105) - 105) / 2;
            img.width(105);
            img.css('margin-top', (shift?-shift:0));
        }
    });

    img.attr('src', oUrl);
    img.parent().attr('style', null);
});

我觉得这很奇怪,因为即使缓存的图像确实会立即加载,IE 怎么会在执行范围的中间触发回调?

猜猜,在 src 替换之前放置与样式相关的代码也应该有效,但我没有确认。

img.attr('style', null);
img.attr('src', oUrl);

希望这可以帮助!

于 2013-03-14T14:27:50.760 回答