Resize a div element to its background image size

前端 未结 6 650
忘了有多久
忘了有多久 2021-01-04 11:24

Is it possible to make a

adapt to its background image? I mean to maintain the proportions width and height.

Clarification:

6条回答
  •  甜味超标
    2021-01-04 11:49

    Ok, my solution is a little bit tricky, but it works. It's a javascript and involve jquery as you wanted. The idea is to create a new image, add it to the DOM, waits till it loads and gets its dimensions. After that the new image is removed and the width and height are applied to the original img tag. Here is a js fiddle demonstrating the workaround http://jsfiddle.net/krasimir/bH5JZ/5/

    And here is the code:

    $(document).ready(function() {
        var image = $("#image");
        var imageurl = image.css("background-image").replace(/url/, '').replace(/\(/, '').replace(/\)/, '');
        var body = $("body");
    
        var newimage = $('');
        newimage.css("display", "none");
        body.append(newimage);
        newimage.on("load", function() {
            var w = $(this).width();
            var h = $(this).height();
            image.css("width", w);
            image.css("height", h);
            newimage.remove();
        });
    });
    

    And the css:

    #image {
        margin: 0px auto;
        background-image:url('http://www.w3.org/html/logo/downloads/HTML5_Logo_512.png');
        background-repeat:no-repeat;
        background-size:100%;
        background-color:yellow;
    }
    

提交回复
热议问题