简体   繁体   English

将div元素粘贴到屏幕顶部

[英]make a div element stick to the top of the screen

I have wrote a script to detect when I reach the div element which is a navigation bar and then I change it's css to position fixed and top 0 so it will be fixed to the top, the problem that it doesn't do that, it acts like scroll to top and it jumps to the beginning of the screen. 我写了一个脚本来检测何时到达导航栏的div元素,然后将其css更改为fixed和top 0的位置,这样它将固定在top上,问题是它没有做到这一点,就像滚动到顶部一样,它跳到屏幕的开头。 (it's flickers) (忽悠)

Javascript 使用Javascript

        var currentScrollTop = 0;
        var barMenuOriginalTopPos = $('#navigation').offset().top;
        console.log('original:' + barMenuOriginalTopPos);
        $(window).scroll(function() {

            currentScrollTop = $(window).scrollTop();
            console.log(currentScrollTop);
            if(currentScrollTop >= barMenuOriginalTopPos && $('#navigation').hasClass('fixElementToTop') == false){
                $('#navigation').addClass('fixElementToTop');
            }
            else if(currentScrollTop < barMenuOriginalTopPos && $('#navigation').hasClass('fixElementToTop') ){
                $('#navigation').removeClass('fixElementToTop');
            }
        });

CSS CSS

.fixElementToTop { position: fixed; top:0; z-index:100;}

Why 为什么

Here an non flickering solution via a jQuery plugin: 这里是通过jQuery插件的非闪烁解决方案

$(document).ready(function() {
    $('#fixedElement').scrollToFixed({ marginTop: 0 });
});

Live example : http://bigspotteddog.github.com/ScrollToFixed/ 实时示例http : //bigspotteddog.github.com/ScrollToFixed/
Plugin's website : https://github.com/bigspotteddog/ScrollToFixed/ 插件的网站https : //github.com/bigspotteddog/ScrollToFixed/

a css fixed bar on top of the screen 屏幕顶部的css固定栏

<div style="position:fixed;top:10px;left:10px">Nav bar</div>

Review: 评论:

sorry i didn't understand your initial question, here it goes, to avoid it flicking you should start the object with a fixed position, lets say: 抱歉,我不明白您的最初问题,为了避免它轻弹,您应该以固定位置启动对象,可以这样说:

<div style="height:120px">XXX</div>
<div id="navigation" style="position: fixed; top:120; z-index:100;">Navigation</div>
<div class="win" style="border: 1px solid; height: 900px;"></div>

the code: 编码:

$(window).scroll(function() {
    currentScrollTop = 120-$(window).scrollTop();
    console.log(currentScrollTop);
    if (currentScrollTop<0) currentScrollTop=0
    $("#navigation")[0].style.top=currentScrollTop+"px";
});​

Set this line 设置这条线

var barMenuOriginalTopPos = $('#navigation').offset().top;

as

var barMenuOriginalTopPos = $('#navigation').offset().top + 6;

Refer LIVE DEMO 参考现场演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM