放入尺寸要求功能

时间:2018-03-16 05:38:13

标签: javascript jquery

我对JavaScript方面有点新鲜。

我试图在我的代码中包含一个条件语句,以便它只适用于768px以上的屏幕尺寸

$(window).on('scroll', function () {
      if ($(window).scrollTop() > 75) {
            $('#anim-nav').addClass('bg-fill').removeClass('white').addClass('black');
      } 
      else {
           $('#anim-nav').removeClass('bg-fill').removeClass('black').addClass('white');
      }
});

并包含

if ($(window).width() > 768) 

3 个答案:

答案 0 :(得分:0)

虽然你的问题不是很详细,但我猜你想在给定条件下执行你的部分功能。

你应该尝试:

$(window).on('scroll', function(){
 if ($(window).width() > 768)
 {
     if ($(window).scrollTop() > 75) 
     {
        $('#anim-nav').addClass('bg- 
        fill').removeClass('white').addClass('black');
     } 
     else 
     {
        $('#anim-nav').removeClass('bg- 
        fill').removeClass('black').addClass('white');
     }
 } 
 });

另外,$(document).width()与$(window).width()不同。可能也想尝试一下。 Reference

答案 1 :(得分:0)

在检查scrollTop之前添加条件,如下所示。

$(window).on('scroll', function () {
   if($(window).width() > 768) {    
      if ($(window).scrollTop() > 75) {
        $('#anim-nav').addClass('bg-fill black').removeClass('white');
      } else {
         $('#anim-nav').removeClass('bg-fill black').addClass('white');
      }
   }   
});

以上代码仅在窗口宽度> 1时才有效。您可以在下面的代码片段中查看相同的内容。我只是在scrollTop > 70和窗口宽度>时应用了一些背景颜色绿色。 768.此外,您可以在一个简短的时间内添加/删除多个类,无需每次都使用add/removeClass。这是Fiddle Version.

$(window).on('scroll', function () {
  if($(window).width() > 768) {    
   if ($(window).scrollTop() > 75) {
      $('#anim-nav').addClass('bg-fill black').removeClass('white');
    } else {
      $('#anim-nav').removeClass('bg-fill black').addClass('white');
    }
 }   
});
.bg-fill {
  background:green;
}
.white {
  color:black;
}
.black {
  color:white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="anim-nav">
<p>
This is the test paragraph
</p><p>
This is the test paragraph
</p><p>
This is the test paragraph
</p><p>
This is the test paragraph
</p><p>
This is the test paragraph
</p><p>
This is the test paragraph
</p><p>
This is the test paragraph
</p><p>
This is the test paragraph
</p><p>
This is the test paragraph
</p><p>
This is the test paragraph
</p><p>
This is the test paragraph
</p><p>
This is the test paragraph
</p><p>
This is the test paragraph
</p><p>
This is the test paragraph
</p><p>
This is the test paragraph
</p>
</div>

答案 2 :(得分:0)

如果您正在考虑使用屏幕宽度,最简单的解决方案是使用window.matchMedia

if (window.matchMedia('(min-width: 768px)').matches) {
    alert('wide');
} else {
    alert('narrow');
}

适用于所有现代浏览器以及IE&gt; = 10。

有关详细信息,请参阅https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia

相关问题