简体   繁体   中英

Resizing SVG images in HTML according to window size

I have a logo for my project that i wish to place at the top of my web page. The logo is in SVG format, default size being 1280x256 px. I wish to have this image be resized when the window size is changed. How can I do this? Will I need jQuery or can this be done with simple JavaScript?

There are actually numerous ways to achieve that. Which one to choose depends on what behavior you want to have. Some examples (assuming your img has the ID image ):

1. CSS using relative sizes:

#image { width: 10%; }

The image has always 10% of the screen width and is adjusted automatically.

2. CSS using media queries:

#image { width: 100px; }
@media (min-width: 600px) {
    #image { width: 300px; }
}

The image is 300px wide if the screen is wider than 600px, else it's 100px wide. The width is adjusted automatically, but will "jump" to its new value.

3. jQuery:

$(window).resize(function(){
    var w = $(window).width();
    $("#image").width(w * 0.1);
});

This is equivalent to example #1. Note that you can do your own calculations in JS however you want, so this solution is more flexible than CSS (but probably makes resizing slower). The same goes for #4.

4. Plain JavaScript:

window.onresize = function(event) {
    var w = 0;
    if (window.innerWidth != null) {
        w = window.innerWidth;
    }
    else if (document.body != null) {
        w = document.body.clientWidth;
    }
    document.getElementById("image").style.width = (w >= 600) ? 300 : 100;
};

This is equivalent to example #2.


Besides, jQuery IS JavaScript, but many people think it's something like an alternative... jQuery is just a way to make JavaScript development a lot more comfortable in many situations (as you may have noticed in the examples above). ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM