修复了 div 在移动设备上向下滚动时显示的问题

fixed div showing when scrolling down on mobile

我网站上的固定菜单有问题。这个想法是它在向下滚动 200px (#menu) 后保持在顶部。所以我创建了一个仅在 200px (#menu-scroll) 之后显示的附加菜单,并在向上滚动时消失。所有这一切都与我找到的 js 解决方案有关,而且效果很好。现在的问题是网站的移动版本。现在,在我的 phone 上向下滚动 200 像素后,总是在 display:none 中的 div 出现了。我需要的是激活#menu-scroll 的代码在移动设备上不再有效,因此 div 与 display:none 保持不可见。我想答案是在 js 中,但我不知道 js。所以,请提供任何帮助。

jsfiddle: jsfiddle.net/695q9tdx/

我的网站(尝试在手机上观看): http://armandorodriguez.pe/uh/

谢谢。

一个简单的解决方法是确定宽度断点并将其包含在 js 周围的 if 语句中。

/* set breakpoint for mobile device */
var breakpoint = 777px;

/* only execute menu code if larger than breakpoint */
if($(window).width() > breakpoint){

    $(window).scroll(function(){
      if($(window).scrollTop() > 200){
          $("#menu-scroll").fadeIn("fast");
      }
     });
     $(window).scroll(function(){
      if($(window).scrollTop() < 200){
          $("#menu-scroll").fadeOut("fast");
      }
    });
}

那么你可以做的是在页面加载时设置它,如果它是一个 mobile/tablet 设备甚至不创建滚动事件监听器。

实现这一点的最简单方法是使用随 JS Navigator 对象发送的 user-agent 字符串。

// This function checks if the userAgent property matches any
// of the typical mobile/tablet devices, separated by the pipeline '|'
// character. 
// If no matches are found, the .match function returns null
// So if (null == null) or (null != null) then we can have a 
// simple boolean return value
function isDesktop() {
  var regexStr = /Android|webOS|iPhone|iPod|iPad|Blackberry/i;
  return (navigator.userAgent.match(regexStr) == null)
}

现在,如果您将该功能包含在页面加载中作为控制 scroll 事件逻辑的一种方式,您几乎可以在 desktop/mobile 设备上禁用该操作:

// Now that we have a way to check if the client is on a Desktop
// on page load, we can setup a scroll event listener only if 
// he/she isn't on a tablet/mobile device.
if (isDesktop()) {

  // **ANYTHING** wrapped within the function(){} statement
  // parameter you pass into the $(x).scroll() function **WILL**
  // get executed on each event fire, so you can include multiple
  // logic checks or functions within it. 
  // Keep in mind though, the more weight added into an event fire
  // can cause lag on the client side, which is why I recommend 
  // adding an event decoupler in the future
  $(window).scroll(function(){
    if ($(window).scrollTop() > 200) {
      $("#menu-scroll").fadeIn("fast");
    }
    else if ($(window).scrollTop() < 200) {
      $("#menu-scroll").fadeOut("fast");
    }
  });
}

我会推荐 adding/removing 来自 #menu-scroll 的一些特殊 class 名称,以免在用户滚动时不断调用 fadeInfadeOut。这样,当您正在收听滚动事件时,您实际上可以将逻辑添加到 只有 淡入或淡出,如果它们具有相反的 class 名称。

另外,再多说一句。这只会像我在页面加载中所说的那样起作用。加载页面后,如果您将浏览器的大小调整为更小的宽度或测试不同的设备 (即使用 Chrome 开发人员工具) 将不会启用侦听器。