如何在 WordPress 中仅当视口大于 1000px 时才执行一段 jquery 代码

How to execute some piece of jquery code only when the viewport is above 1000px in WordPress

我需要在视口超过 1000 像素及以上时执行一些 jquery 代码,但我无法让它工作。请有人告诉我我做错了什么。

jQuery(document).ready(function($) {
  $(window).on('scroll', function() {
    var y = $(window).scrollTop();
    var width = $(window).innerWidth();

    if (window.location.pathname == '/') {
      if ($(window).innerWidth() > 1000 && y > 0) {
        $('#top').fadeIn();
        $('#header-space').fadeIn();
      } else {
        $('#top').fadeOut();
        $('#header-space').fadeOut();
      }
    } else {}
  });
});

你真的不需要 $(window).innerWidth() 你可以使用普通的 js。

window.innerWidth

如果你使用 Jquery 它会使用

$( window ).width();

https://api.jquery.com/width/

jQuery(document).ready(function($) {
  $(window).on('scroll', function() {
    var y = $(window).scrollTop();
    var width = $(window).width();

    if (window.location.pathname == '/') {
      if (width > 1000 && y > 0) {
        $('#top').fadeIn();
        $('#header-space').fadeIn();
      } else {
        $('#top').fadeOut();
        $('#header-space').fadeOut();
      }
    }
  });
});

试试这个对我有用..

if($(window).width() > 1000){
   $('#top').fadeIn();
    $('#header-space').fadeIn();
}
else{
    $('#top').fadeOut();
    $('#header-space').fadeOut();
}