Disable Skrollr for mobile device ( <767px )

后端 未结 6 2067
暖寄归人
暖寄归人 2021-02-02 01:59

Firstly would like to thanks @prinzhorn for such an amazing and powerful library. My question: I have implemented a Skrollr parallax background to the header of my website but I

6条回答
  •  情歌与酒
    2021-02-02 02:30

    The .destroy() method is the correct method to use; however, I would approach this differently than the accepted answer. Initializing the skrollr instance a second time to destroy it is unnecessary and performance can be improved using the .get() method, like so:

    $(function () {
      // Init function
      function skrollrInit() {
        skrollr.init(yourOptions);
      }
    
      // If window width is large enough, initialize skrollr
      if ($(window).width() > 767) {
        skrollrInit();
      }
    
      // On resize, check window width, if too small
      // and skrollr instance exists, destroy;
      // Otherwise, if window is large enough
      // and skrollr instance does not exist, initialize skrollr.
      $(window).on('resize', function () {
        var _skrollr = skrollr.get(); // get() returns the skrollr instance or undefined
        var windowWidth = $(window).width();
    
        if ( windowWidth <= 767 && _skrollr !== undefined ) {
          _skrollr.destroy();
        } else if ( windowWidth > 767 && _skrollr === undefined ) {
          skrollrInit();
        }
      });
    });
    

    Skrollr never gets initialized a second time if it currently exists and is only destroyed if it exists. This avoids any bugs you may find by the brief moment between initializing and destroying (I speak from experience on this).

提交回复
热议问题