문제

Today I've encountered an interesting situation with IE8 while I was trying to manipulate images.

I'm replacing loaded images by changing their url and when they get loaded I'm trying to properly squeeze them and center at viewport element (new images are not square as their predecessors). But in IE8 (haven't tested IE7, and heard from colleagues IE9 - is all fine) images are not scaled, they just drop at their original size and my

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

are simply ignored. Here is the code snipped with the problem.

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

Please look for my self-answer for the solution.

도움이 되었습니까?

해결책

The problem turned out to be IE image cache and the way it handles event handlers. The css were cleared by myself at this line img.attr('style', null);. So simply moving this style deletion at top solved the problem.

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

I find this quite odd, cause even if cached images do get loaded immediately how come IE triggers callback in the middle of the execution scope?

Guess, placing style related code just before the src replacement should also work, but I didn't confirm that.

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

Hope this helps!

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top