开发者

How can I set the max width for images in a page in a cross-browser way?

How can I set the max width for images in a page in a cross-browser way开发者_StackOverflow中文版 using CSS or Javascript?


img.limitsize { max-width: 640px; }

Works for all modern browsers. Doesn't work on IE6. If you need IE6 support you'd have to use JS, eg.:

// IE-6-only function to implement max-width
// (you can do min- and height similarly)
//
function MaxWidthFix(element) {
    var width= element.currentStyle['max-width'];

    function update() {
        element.style.width= width;
        var wmax= element.offsetWidth;
        element.style.width= 'auto';
        var wauto= element.offsetWidth;
        if (wauto>wmax)
            element.style.width= width;
    }

    // If width or max-width is set in % or em, window and font resizes
    // might change sizes, requiring an update
    //
    window.attachEvent('onresize', update);
    setTimeout(update, 1000);
    update();
}

if (!('maxWidth' in document.body.style)) {
    var imgs= document.getElementsByTagName('img');
    for (var i= imgs.length; i-->0;)
        if (imgs[i].className.indexOf('limitsize')!==-1)
           MaxWidthFix(imgs[i]);
}


In Css use

img{width: 400px;}

But use your own size.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜