粘性标题捕捉到顶部到早期
Sticky header snapping to top to early
我一直在玩这个代码。 我在我的网站上实现了一个粘性导航,一旦用户滚动时标题消失,它就会激活。 标题div 位于导航div 上方。 粘性部分工作正常,但它激活得太快了。一旦我开始滚动,它就会立即捕捉到顶部,然后在标题再次进入视野后不会捕捉到它的原始位置。
这是使其工作的jquery:
(function($) {
var $body,
$target,
targetoffsetTop,
resizetimer,
stickyclass = 'sticky'
function updateCoords() {
targetoffsetTop = $target.offset().top
}
function makesticky() { //Sets the sticky class to activate once
var scrollTop = $(document).scrollTop() //the scroll offset is greater than
if (scrollTop >= targetoffsetTop) { //how far the div is from the top.
if (!$body.hasClass(stickyclass)) {
$body.addClass(stickyclass)
}
} else {
if ($body.hasClass(stickyclass)) {
$body.removeClass(stickyclass)
}
}
}
$(window).on('load', function() {
$body = $(document.body)
$target = $('#header_lg') //This is the target div that get's sticky
updateCoords()
$(window).on('scroll', function() {
requestAnimationFrame(makesticky)
})
$(window).on('resize', function() {
clearTimeout(resizetimer)
resizetimer = setTimeout(function() {
$body.removeClass(stickyclass)
updateCoords()
makesticky()
}, 50)
})
})
})(jQuery)
.CSS:
#header_lg { //Before sticky
width: 100%;
height: 75px;
padding: .7%;
background-color: blue;
-webkit-transition: height 1s, width 1s;
-moz-transition: height 1s, width 1s;
transition: height 1s, width 1s;
}
body.sticky #header_lg { //After sticky
position: fixed;
top: 0;
left: 0;
height: 100px;
width: 100%;
}
我对javascript相当陌生,所以专家对代码为什么不能正常工作的任何建议将不胜感激。 如果它很重要,则页面采用引导格式,因此它位于 visible-lg
类中,其中有一个设置为 style="width:100%; margin:0; padding:0;"
的container
类。 HTML 代码只是一个带有一些填充文本的空div。
你没有正确编写你的CSS注释(与js不同):
试试这个:(感谢@Toni在这里我分叉演示的她有用的笔)
#header_lg { /*Before sticky*/
width: 100%;
height: 75px;
padding: .7%;
background-color: blue;
-webkit-transition: height 1s, width 1s;
-moz-transition: height 1s, width 1s;
transition: height 1s, width 1s;
}
body.sticky #header_lg { /*After sticky*/
position: fixed;
top: 0;
left: 0;
height: 100px;
width: 100%;
}
相关文章:
- 花式盒子3.0标题在顶部
- 滚动然后修复到 html 中的顶部标题
- 试图在CSS中以顶部标题居中链接,但不会移动
- 幻灯片顶部带有标题的柔性滑块
- 粘性标题捕捉到顶部到早期
- 使粘性标题粘在顶部
- 如何将剑道网格标题文本保持在顶部
- 如何在输入单击时出现键盘时使标题粘在顶部 (iPhone)
- 通过单击任何单元格或表格数据及其左侧和顶部标题进行查找
- 如何通过jquery将滚动头文本加载到顶部固定标题区域
- jQuery:在滚动时切换标题类,如果页面不在顶部
- 将红色标题附加到边框顶部
- WordPress-标题位置顶部,左&正确的
- 如何在外部网站的顶部显示webapp的标题栏
- 如何防止任何iframe或任何其他脚本在顶部窗口更改文档的标题
- 在页面顶部显示标题-滚动事件重新触发问题
- 使用换行标题时,在顶部显示标题文本
- 纸卷标题面板,工具栏到达顶部后保留
- Angular注入了长内容的页面会让整个页面在页面顶部下方加载,切断了页面标题
- 如何仅按顶部标题行对表进行排序