Contain an image within a div?

后端 未结 7 819
北荒
北荒 2020-12-13 00:08

I want to contain an image into a 250 x 250 div, forcing the image to resize but not stretch. How can I do this? By the way, the image will usually be bigger than the div it

7条回答
  •  盖世英雄少女心
    2020-12-13 00:44

    Here is javascript I wrote to do just this.

    function ImageTile(parentdiv, imagediv) {
    imagediv.style.position = 'absolute';
    
    function load(image) {
        //
        // Reset to auto so that when the load happens it resizes to fit our image and that
        // way we can tell what size our image is. If we don't do that then it uses the last used
        // values to auto-size our image and we don't know what the actual size of the image is.
        //
        imagediv.style.height = "auto";
        imagediv.style.width = "auto";
        imagediv.style.top = 0;
        imagediv.style.left = 0;
    
        imagediv.src = image;
    }
    
    //bind load event (need to wait for it to finish loading the image)
    imagediv.onload = function() {
        var vpWidth = parentdiv.clientWidth;
        var vpHeight = parentdiv.clientHeight;
        var imgWidth = this.clientWidth;
        var imgHeight = this.clientHeight;
    
        if (imgHeight > imgWidth) {
            this.style.height = vpHeight + 'px';
            var width = ((imgWidth/imgHeight) * vpHeight);
            this.style.width = width + 'px';
            this.style.left = ((vpWidth - width)/2) + 'px';
        } else {
            this.style.width = vpWidth + 'px';
            var height = ((imgHeight/imgWidth) * vpWidth);
            this.style.height = height + 'px';
            this.style.top = ((vpHeight - height)/2) + 'px';
        }
    };
    
    return {
        "load": load
    };
    

    }

    And to use it just do something like this:

     var tile1 = ImageTile(document.documentElement, document.getElementById("tile1"));
     tile1.load(url);
    

    I use this for a slideshow in which I have two of these "tiles" and I fade one out and the other in. The loading is done on the "tile" that is not visible to avoid the jarring visual affect of the resetting of the style back to "auto".

提交回复
热议问题