Domanda

I was having issues with background-size in IE, so I found a JavaScript that allows it to work in IE, but I only want background-size applied if the screen width goes below 768 pixels.

Here is my current script:

$(window).resize(function() {
    if($(window).width() > 768)
       jQuery('#header').css( "background-size", "cover" );
});

This works once you start resizing, but once you get below 768 it doesn't remove background-size and the initial state does not have background size either. Any ideas? Thanks!

È stato utile?

Soluzione

Your answer is nearly correct. All you need to do is add an else.

$(window).resize(function() {
    if($(window).width() > 768) {
       jQuery('#header').css( "background-size", "cover" );
    } else {
       jQuery('#header').css( "background-size", "whatever" );
    }
});

I'm concerned about you writing all over the place jQuery so what you can do is also:

jQuery(function( $ ) { // DOM ready and secured jQuery's $ alias

  // Use freely $ alias
  var $header = $('#header'); // Cache your selectors
  $(window).resize(function() {
    $header.css({backgroundSize:$(this).width()>768?"cover":"whatever"});
  });

  // Other $ code here

});

Altri suggerimenti

No need to javascript it, just use css and mediaqueries. This is a lot faster than jQuery/javascript, and is exactly for this type of situation. Especially on mobiles you will can notice this when rotating the device. Also, older browsers will be less jaggy on resize.

#header{
    /* style for the older browsers, also basic info like maybe height/width */
} 

@media screen {
    #header{
        background-size : cover;
        /* Other css, not defined in the #header{} above, for modern browsers */
    } 
}

Small note: Mediaqueries will not work on older browsers. You can use this to your advantage and style the modern browsers only in the mediaquery.
Please bare in mind, background-size doesn't work, so you can not use that

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top