javascript - 使用 Javascript 克隆();使独立标题跟随页面

标签 javascript jquery html css

我的页面上有一个 一个 DIV 的 html 结构,其中包含 两个其他 DIVS,其中第一个是较小的 header 和另一个是 navigation 栏 (#main-template-navigation)。这两个 div 都是静态的,因此当您滚动页面时它们不会跟随。我现在要做的是让导航 div 跟随页面滚动。我正在使用下面的代码来执行此操作,但是当位置更改为固定时,网站会跳起来,这不是那么流畅。

所以我的问题是如何让它“平滑”?我一直在尝试使用 clone(); 函数,但只要我没有单独的 div 将其附加到我想避免的地方,它就不起作用。

$(function() {
    var stickyHeaderTop = $('#main-template-navigation').offset().top;

    $(window).scroll(function() {
        if( $(window).scrollTop() > stickyHeaderTop ) {

            $('#main-template-navigation').css({position: 'fixed', top: '0px'});

        } else {

            $('#main-template-navigation').css({position: 'static', top: '0px'});

        }
    });
});

最佳答案

这是解决问题的一种方法: 添加固定时在顶部添加一个“缓冲区”div,并在删除时将其删除。缓冲区 div 高度与导航高度匹配

演示:https://jsfiddle.net/4vbzvxd7/5/

$(function() {
    var stickyHeaderTop = $('#main-template-navigation').offset().top;

    $(window).scroll(function() {
        if( $(window).scrollTop() > stickyHeaderTop ) {

            $('#main-template-navigation').css({position: 'fixed', top: '0px'});

            if(!$('#main-template-navigation-container').length){
                $('<div/>',{
                    id: 'main-template-navigation-container',
                    css: {
                        height: $('#main-template-navigation').height()   
                    }
                }).prependTo('body');
            }

        } else {
            $('#main-template-navigation').css({position: 'static', top: '0px'});
            $('#main-template-navigation-container').remove();
        }
    });
});

关于javascript - 使用 Javascript 克隆();使独立标题跟随页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29474835/

相关文章:

javascript - Angular 多维数组

javascript - 在 JavaScript 中禁用文本选择器

jquery - 访问各个页面的选项卡内容jquery mobile

python - 为什么我的 urls.py 不起作用?

html - 如何将输入限制为 4 位数字

Javascript 倒计时进展缓慢?

javascript - angular 2无法引用函数内的变量

javascript - blueimp jquery-file-upload 如何检测按下取消按钮?

javascript - 单击具有多个系列的 highcharts 上的事件

html - 在移动设备上显示多个元素的 Owl Carousel