質問

I'm trying to trigger a class removal based on two conditions : a window with less than 760 px and a scroll > 0.

Here's my script:

<script type="text/javascript">
    $(window).resize(function() {
        var $windowWidth = window.innerWidth
    }
    $(window).scroll(function() {
        if (($(window).scrollTop() > 0) && ($windowWidth <= 760)) {
            $("nav").removeClass("horizontal").addClass("vertical");
        }
    });
    });
</script>

Thanks for your help!

役に立ちましたか?

解決

LIVE DEMO

You don't need 2 classes, only one, the .vertical supposing the default is the other.

<nav class="horizontal">NAV</nav>

You were close, create a function:

function checkWin(){
  var winInnW = window.innerWidth;
  var winScrT = $(window).scrollTop();
  var s0w760  = winScrT>0 && winInnW<=760; // Boolean
  $("nav").toggleClass("vertical", s0w760);
}

checkWin(); // on DOM ready also
$(window).on('resize scroll', checkWin);


if you feel comfortable here's a oneliner

function checkWin(){
   $("nav").toggleClass("vertical", $(window).scrollTop()>0 && window.innerWidth<=760);
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top