简体   繁体   中英

Swap a background image for media query with javascript

I'm using Vegas Background Slidehow and I would like to swap the background image when the user sees the Landing Page in a smartphone or tablet, the code by default is:

$('body').vegas({
    delay: 15000,
    timer: false,
    transitionDuration: 2000,
    slides: [
        { src: 'img/background/0.jpg' },
        { src: 'img/background/1.jpg' },
        { src: 'img/background/2.jpg' }
    ],
    transition: 'swirlRight',
    animation: 'kenburns'
});

How can I write a javascript code which the background image swap in media query? Thanks!

You could append a style to the head element of the page like this:

$('head').append('<style>@media (min-width: 1000px){ .my-style{ background-color: #000; } }</style>');

Though as mentioned before by r00k, for media queries you don't need javascript. Just inspect the page and check what code the slider plugin generates and personalize with css the slide items. Best Regards.

To give a static background image you can use CSS only, there is no need of Javascript to do that.

@media(max-width:768px){ 
    .vegas{ 
        background-image:url("/assets/x/y/z"); 
    }
}

This CSS will apply only on the screen sizes whose width is smaller then or equal to 768px which is generally standard size for tablets, you can also define min-width attribute to the media query like this.

@media(max-width:768px) and (min-width: 520px){ 
    .vegas{ 
        background-image:url("/assets/x/y/z"); 
    }
}

this CSS styling will be applicable to only devices with width greater then or equal to 520px & smaller then or equal to 768px. You can use combination of both the things to achieve the styling for different devices sizes.

Cheers Vaibhav

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