首页 > 解决方案 > 当屏幕宽度小于 810px 时,如何删除 relax 类?

问题描述

我的问题是,当屏幕尺寸高于 810 像素时,我想将视差效果(rellax类)添加到类home-content中,并在低于 810 像素时将其删除。另外,如果可能的话,我希望能够在启用data-rellax-speed = "-4"时添加。rellax

问题是我有错误:肯定是因为它在 HTMLrellax.js:141 Rellax: The elements you're trying to select don't exist.中找不到.relax

这是该部分的HTML代码.home-content

<section class="home content" id="home">
        <div class="max-width">
            <div class="home-content">
                <div class="text-1 stagger1">&#128075; Bonjour, je suis</div>
                <div class="text-2 stagger1">Eric</div>
                <div class="text-3 stagger1">Et je suis un <span class="crimson" id="typing"></span></div>
                <a class="stagger2" href="#contact">Me contacter</a>
            </div>
        </div>
</section>

这是到目前为止的 JS(我正在使用 Rellax.js 来实现视差):

$(document).ready(function(){
 // Parallax
    var rellax = new Rellax('.rellax');

    if(window.innerWidth < 810){
        $('.home-content').removeClass('rellax');

    }
})

$(window).resize(function(){
    if(window.innerWidth < 810){
        $('.home-content').removeClass('rellax');
    }else{
        $('.home-content').addClass('rellax');
    }
});

标签: javascripthtmljquery

解决方案


在引用之前检查relax类或元素:

var rellax;

$(document).ready(function(){
    if ($('.rellax').length) rellax = new Rellax('.rellax');

    if(window.innerWidth < 810) {
        $('.home-content').removeClass('rellax');
    }
})

$(window).resize(function(){
    if(window.innerWidth < 810) {
        rellax.destroy(); 
        $('.home-content').removeClass('rellax');
        
    } else {
        $('.home-content').addClass('rellax');
        rellax = new Rellax('.rellax')
    }
});

推荐阅读