jQuery 如果窗口大小调整为更大的分辨率,则销毁 iDangerous Swiper 或在调整为较小的分辨率时调用它

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21538056/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 01:37:39  来源:igfitidea点击:

destroy iDangerous Swiper if window is resized to a bigger resolution or call it when resized to a smaller resolution

jqueryswiper

提问by fksr86

i'm using iDangerous Swiperfor my website in lower resolutions. here is how i'm calling it:

我正在以较低的分辨率为我的网站使用iDangerous Swiper。这是我的称呼:

var resolution = 670;
if ($(window).width() < resolution) {
var mySwiper = $('.swiper-container').swiper({
    mode:'horizontal',
    loop: true,
    grabCursor: true,
    paginationClickable: true
});

so, when you access it in a desktop browser, the swiper will not be called. what i want to do is to "turn it on" if the user resizes the window to a size smaller than resolutionor destroy it if the user accesses it in a small window size and then resizes it to bigger than resolution. i tried this, but it didn't work:

因此,当您在桌面浏览器中访问它时,不会调用 swiper。我想要做的是“打开它”,如果用户将窗口resolution调整为小于resolution. 我试过这个,但没有用:

$(window).resize(function(){
    if ($(window).width() < resolution) {
        if(typeof(mySwiper) === "undefined" ) {
            var mySwiper = $('.swiper-container').swiper({
                mode:'horizontal',
                loop: true,
                grabCursor: true,
                paginationClickable: true
            });
        }
    } else {
        if (typeof(mySwiper) !== "undefined" ) {
            mySwiper.destroy();
        }
    }
});

two undesirable things happen:

发生了两件不受欢迎的事情:

  1. if the user is in a small resolution and resizes it to a resolution that still calls the swiper, it restarts the swiper.
  2. if the user is in a small resolution and resizes it to a bigger resolution, it is not destroyed.
  1. 如果用户处于小分辨率并将其调整为仍然调用 swiper 的分辨率,它会重新启动 swiper。
  2. 如果用户处于小分辨率并将其调整为更大的分辨率,则它不会被破坏。

i thing my problem is the typeof. i don't know much how variables work when they are called like this: $('.swiper-container').swiper().

我的问题是typeof。我不知道多少变量是如何工作的时候,他们被称为是这样的:$('.swiper-container').swiper()

how do i "uncall" swiper and how not call it if it was already called?

我如何“取消呼叫”swiper,如果它已经被调用,如何不调用它?

回答by user2048176

My solution:

我的解决方案:

var mySwiper = undefined;
function initSwiper() {
    var screenWidth = $(window).width();
    if(screenWidth < 992 && mySwiper == undefined) {            
        mySwiper = new Swiper('.swiper-container', {            
            spaceBetween: 0,
            freeMode: true
        });
    } else if (screenWidth > 991 && mySwiper != undefined) {
        mySwiper.destroy();
        mySwiper = undefined;
        jQuery('.swiper-wrapper').removeAttr('style');
        jQuery('.swiper-slide').removeAttr('style');            
    }        
}

//Swiper plugin initialization
initSwiper();

//Swiper plugin initialization on window resize
$(window).on('resize', function(){
    initSwiper();        
});

And it worx! :)

它工作!:)

回答by Geoff Foley

I was having the same problem and found that as soon as the width was beyond my max width, mySwiper was again undefinedand therefore the if(typeof)statement always returned false.

我遇到了同样的问题,发现只要宽度超过我的最大宽度,mySwiper 就会再次出现undefined,因此if(typeof)语句总是返回false.

I found another hybrid solution with the fired[]array below and also realized that while the destroy()method may be executing in my example, the swiper itself had added a style attribute to the wrapper and slide DIVs which was persisting after the destroy method was called and only went away with a page refresh. After I added the removeAttr()method calls on the two DIVs, everything worked as expected.

我找到了另一个带有fired[]下面数组的混合解决方案,并且还意识到虽然该destroy()方法可能正在我的示例中执行,但 swiper 本身已向包装器和幻灯片 DIV 添加了一个样式属性,该属性在调用 destroy 方法后仍然存在并且仅消失与页面刷新。在removeAttr()两个 DIV 上添加方法调用后,一切都按预期工作。

Your mileage may vary.

你的旅费可能会改变。

$(window).on('resize', function ()
{
    if ($(this).width() <= 383 && !fired[0])
    {
        fired[0] = true;
        fired[1] = false;

        mySwiper = $('.swiper-container').swiper({ mode: 'horizontal', loop: false, wrapperClass: 'swiper-wrapper', slideClass: 'swiper-slide' });
    }
    else if ($(this).width() >= 384 && !fired[1])
    {
        fired[0] = false;
        fired[1] = true;

        mySwiper.destroy();

        $('.swiper-wrapper').removeAttr('style');
        $('.swiper-slide').removeAttr('style');
    }
});

回答by breakone

I had the same problem and took a similar solution:

我遇到了同样的问题并采取了类似的解决方案:

init function:

初始化函数:

var mySwiper;

my resize function:

我的调整大小功能:

if(jQuery(window).width() < 672) {
    if (typeof mySwiper == 'undefined') {
        mySwiper = new Swiper('#myId', {
            calculateHeight: true
        });
    }
} else {
    if (typeof mySwiper != 'undefined') {
        // destroy and delete swiper object
        mySwiper.destroy();
        mySwiper = undefined;

        // reset styling for wrapper and slides
        jQuery('.swiper-wrapper').removeAttr('style');
        jQuery('.swiper-slide').removeAttr('style');
    }
}

回答by David D

For anyone still having problems destroying and initialising Swiper on demand try calling reInit() with a slight delay.

对于在按需销毁和初始化 Swiper 仍有问题的任何人,请尝试稍微延迟调用 reInit()。

define Swiper reference on page load

在页面加载时定义 Swiper 引用

var mySwiper;

Start Swiper

启动刷卡

// Set Slider 
        mySwiper = new Swiper ('.swiper-container', {loop: true }); 
 // Run Update after 500ms
        setTimeout(function() { mySwiper.reInit(); },500);    

Destory Swiper

毁灭扫荡者

  if (typeof mySwiper != 'undefined') {  
    mySwiper.destroy();
    mySwiper = undefined;
  }      

If your updating markup through ajax ensure you empty the container first. i.e:

如果您通过 ajax 更新标记,请确保先清空容器。IE:

 if (typeof mySwiper != 'undefined') {  
   mySwiper.destroy();
   mySwiper = undefined;
 }    
 $('#container-with-swiper-markup').html("");

回答by Michael Giovanni Pumo

Okay, so I know I'm late to the party, but I had similar issues and ended up with a solution that works solid.

好的,所以我知道我迟到了,但我遇到了类似的问题,最终得到了一个有效的解决方案。

The story: Swiper needs to run on desktop, but not on mobile (small screens) and should be able to change between them on resize.

故事:Swiper 需要在桌面上运行,但不能在移动设备(小屏幕)上运行,并且应该能够在调整大小时在它们之间进行更改。

Requirements: In my example, I'm using jQuery, Swiper and Modernizr (for media queries, as window width etc is unreliable).

要求:在我的示例中,我使用 jQuery、Swiper 和 Modernizr(对于媒体查询,因为窗口宽度等不可靠)。

JavaScript:

JavaScript:

/*! Michael Pumo - Web Development. http://michaelpumo.com */

(function($, Modernizr) {

    'use strict';

    var state = {

        swiper: false,

        setOrGetDevice: function(device) {

            if (typeof(device) === 'undefined') {
                var mq = Modernizr.mq('only screen and (min-width: 768px)') ? 'desktop' : 'mobile';
                device = mq;
            }

            return device;

        },

        device: function() {

            return state.setOrGetDevice();

        }

    };

    var cache = {

        $window: $(window),
        $swiper: $('.swiper-container'),
        $swiperElements: $('.swiper-container, .swiper-wrapper, .swiper-slide')

    };

    var swiper;

    var app = {

        init: function() {

            app.swiper();

        },

        swiper: function() {

            if(state.device() === 'desktop' && !state.swiper) {

                swiper = cache.$swiper.swiper({
                    parallax: false,
                    initialSlide: 0,
                    direction: 'horizontal',
                    loop: true,
                    autoplay: 3000,
                    speed: 1000
                });

                state.swiper = true;

            } else if(state.device() === 'mobile' && state.swiper) {

                swiper.destroy();
                swiper = undefined;
                cache.$swiperElements.removeAttr('style');

                state.swiper = false;

            }

        }

    };

    $(function() {
        app.init();
    });

    cache.$window.on('resize', function() {

        var mq = Modernizr.mq('only screen and (min-width: 768px)') ? 'desktop' : 'mobile';
        state.setOrGetDevice(mq);
        app.init();

    });

})(window.jQuery, window.Modernizr);

As well as checking the 'device' (in other words, mobile size or desktop size), it checks against a flag I set in state.swiper. As this is a mobile-first approach, this flag is initially set to false.

除了检查“设备”(换句话说,移动设备大小或桌面大小)外,它还检查我在state.swiper. 由于这是移动优先的方法,因此此标志最初设置为false

I know that my explanation is brief, but this works 100% and has the benefit of not initializing Swiper at every stage of the resize, thanks to the flag.

我知道我的解释很简短,但这 100% 有效,并且由于标志,它的好处是不在调整大小的每个阶段初始化 Swiper。

The HTMLwould just be the standard HTMLthat Swiper requires, so that's what you should use if you're going with this solution.

HTML也只是标准的HTML是组队,探索要求,所以这是你应该用什么,如果你这个解决方案会。

Hope it can be of some help to someone.

希望它可以对某人有所帮助。

Thanks, Mikey.

谢谢,米奇。

回答by Arkadyuti Sarkar

I have a better solution which has given by the http://idangero.us

我有一个更好的解决方案,由http://idangero.us 提供



var mySwiper = new Swiper('.swiper-container', {
    // Optional parameters
    direction: 'vertical',
    loop: true
})
if (window.innerWidth > 767) {
    swiper.detachEvents();
}