jquery - NavBar 有点不稳定(jQuery、html、css)

标签 jquery css navbar nav

我的导航栏时不时出现问题。它不会一直发生,这很有趣,但当它发生时它会困扰我。问题是开始时向上/向下滚动时,有时会在打开/关闭时有点滞后。我正在使用谷歌浏览器。

它是使用 html、css 和 jquery 制作的。这是codepan链接: https://codepen.io/JhnSnw/pen/prLwxa

我尝试了我在网上阅读的关于类似问题的某些东西,但它们没有用。任何形式的帮助都很棒。谢谢。

最佳答案

window.scroll 对于每个滚动像素 都会触发(至少在 Firefox 中),我猜这可能会对您的性能产​​生一些影响。为了限制事件的数量,有 dethrottle 或 deboucen。

This webpage有一个很好的插件并且解释得很好:

A Visualization

While $.throttle is designed to throttle callback execution, it behaves slightly differently based on how the no_trailing parameter is used.

Throttled with no_trailing specified as false or unspecified: enter image description here

第一行是触发事件的数量,第二行是可能触发的 detrottled 版本,例如每 50 毫秒(仍然非常快!)。


您可能应用的另一个解决方案是逻辑函数。在您的代码中,您有一个 if/else。如果您滚动,您总是应用 removeClassaddClass 这不是性能的最佳选择。
你可以很容易地记住你是否已经超过了阈值,并且只有当它再次改变时才会触发:

if (scrolled > navHeight){
    if( !scrolledPastThreshold ){
        $('.page-nav').addClass('off-canvas');
        scrolledPastThreshold = true;
    }
} else {
    if( scrolledPastThreshold ){
        $('.page-nav').removeClass('off-canvas');
        scrolledPastThreshold = false;
    }
}  

关于jquery - NavBar 有点不稳定(jQuery、html、css),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45786001/

相关文章:

javascript - 将 Prop 传递给导航栏不会更新组件

javascript - $(...).sortable 不是函数

css - 将 CSS 类添加到 reStructuredText 内部引用

html - 对于不同分辨率的背景图像,表格太长

html - Twitter 的 Bootstrap 2.x 导航栏溢出到 2 行

css - Bootstrap 4 响应式 Navbar 不会提供下拉菜单

jquery - Laravel 5.5 jQuery ajax 方法

javascript - 如何在 JQuery/Javascript 中验证表单

javascript - 在两个不同的类上运行 Javascript Jquery 函数

javascript - 两个不同的链接显示/隐藏具有两个 ID 的 div。如何?