简体   繁体   English

不使用CSS位置的Javascript / jQuery粘性:固定

[英]Javascript / jQuery sticky without using css position: fixed

I'm looking for a Javascript/jQuery plugin for sticky header that will not switch the element's style to position fixed. 我正在寻找一个用于粘滞标头的Javascript / jQuery插件,该插件不会将元素的样式切换为固定位置。 Usually, I'm working with this one http://stickyjs.com/ and it works fine. 通常,我正在使用这个http://stickyjs.com/ ,并且工作正常。

I'm working on a website with jQuery animation and one of my div has a sticky header with width:100%. 我正在使用jQuery动画制作网站,而我的一个div的标题页宽度为100%。 But when I move it to the left (for example), the width:100% is now based on the window's width and not his container. 但是,当我将其向左移动(例如)时,width:100%现在基于窗口的宽度而不是其容器。

So, is there an existing plugin that does the same thing as the others but keep the position: relative and calculate the scrollTop to apply as the margin-top for my sticky header? 因此,是否有一个现有的插件,其功能与其他插件相同,但保持位置:相对并计算scrollTop用作我的粘性标头的页边距?

So, I solved my problem! 所以,我解决了我的问题! Here's my javascript code: 这是我的JavaScript代码:

You have to set top:0px as default 您必须将top:0px设置为默认值

function relative_sticky(id, topSpacing){

if(!topSpacing){ var topSpacing = 0; }

var el_top = parseFloat(document.getElementById(id).getBoundingClientRect().top);
    el_top = el_top - parseFloat(document.getElementById(id).style.top);
    el_top = el_top * (-1);
    el_top = el_top + topSpacing;

    if(el_top > 0){
    document.getElementById(id).style.top = el_top + "px";
    } else{
    document.getElementById(id).style.top = "0px";
    }
}

window.onscroll = function(){

    relative_sticky("your_element_id", 10);
}

It's not very smooth in IE, so I add a delay: 在IE中不是很流畅,因此我添加了一个延迟:

var delay = (function(){
  var timer = 0;
  return function(callback, ms){
    clearTimeout (timer);
    timer = setTimeout(callback, ms);
  };
})();

window.onscroll = function(){

    if(BrowserDetect.browser == "Explorer" || BrowserDetect.browser == "Mozilla"){
    // or your own way to detect browser

        delay(function(){
        relative_sticky("admin_users_head", 31);
        }, 200);
    }
    else{
    relative_sticky("admin_users_head", 31);
    }
}

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

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