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/

相关文章:

ajax - 如何使用 jquery/ajax 在 Spring Form 上填充实体对象值?

javascript - 带有事件的输入框字段出现奇怪的问题

javascript - 如果窗口调整大小时卸载 jquery 函数

html - 我的 Bootstrap 汉堡菜单不显示链接

javascript - 基于 bool 值的淡入/淡出

javascript - 正确附加嵌入播放器的问题

div 内的 CSS div 扩展底部

html - Div 中的元素不会居中

html - Bootstrap 全宽 Navbar 侧面有两种不同的背景颜色

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