简体   繁体   中英

Is it possible to return to a CSS media query declaration from Javascript?

I have a DIV where I adjust the font size in CSS depending on the viewport size:

font-size:1em;
@media only screen and (min-width: 300px) {
    font-size:2em; 
}
@media only screen and (min-width: 600px) {
    font-size:3em; 
}

However, I also have Javascript that changes the font size depending on whether or not the user scrolls down.

$(window).scroll(function () {
    if ($(this).scrollTop() > 1) {
        $('#div').css('font-size', '1em');       
    }
    else {
        $('#div').css('font-size', '3em');
    }
});

The problem is, after the user has scrolled down and up again at least once, the Javascript has set the font-size to 3em , and the @media declarations no longer apply.

Is it possible to make it so that in the Javascript else clause, the style reverts back to what is declared in the CSS and @media conditions?

As I already commented, instead of using .css() which defines inline styles for an element has highest precedence hence you can reset it with nothing but jQuery again which is dirty or might get dirty if you have more than couple of properties to reset/change in if else .

So instead of using .css() you should be using .addClass() and .removeClass() methods and will accomplish well of what you are looking for.

The style you apply to #div overrides the @media declaration so you have to remove the applied style. Use an empty style (ie $('#div').css('font-size', '') ) to remove a css property.

Instead of setting the font-size back to normal with javascript you could set it to 'nothing'. That way the styles defined in your css get applied.

$(window).scroll(function () {
    if ($(this).scrollTop() > 1) {
        $('#div').css('font-size', '1em');       
    }
    else {
        $('#div').css('font-size', '');
    }
});

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