根据窗口滚动更改div的页边距 [英] Change margin top of div based on window scroll

查看:88
本文介绍了根据窗口滚动更改div的页边距的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的页面顶部有一个固定位置的栏.当用户滚动到某个点时,我希望条开始向上移动,就好像它是相对或绝对定位一样.

I have a bar at the top of my page that is position fixed. When the user scrolls to a certain point I want the bar to start moving up as if it was relatively or absolutely positioned.

现在,栏的css从固定变为绝对定位,但是当然,这会将div直接设置到页面顶部.

Right now the css of the bar changes from fixed to absolutely positioned but of course this sets the div straight to the top of the page.

我已经看了很久了,无法理解如何滚动超过_triggerOffset的每个像素一次将栏推高一个像素

I have been looking at this for ages and cannot get my head around how I would push the bar up one pixel at a time for every pixel scrolled past the _triggerOffset

有人可以启发我吗?

function banner(){

    var _barOffset = $('#top-bar').outerHeight(),
        _navOffset = $('#navigation').offset().top,
        _triggerOffset = _navOffset-_barOffset;

    $(window).scroll(function() {

        var _scroll = $(window).scrollTop();

        if (_scroll >= _triggerOffset) {
            $('#top-bar').css({'position':'absolute'});
        }

    });

}

banner();

推荐答案

我做了一个小提琴.

检查这个小提琴

工作演示

Working Demo

$(document).ready(function() {
  var postionToTriggerMove = 500;
  var positioninitial = $(window).scrollTop();
  var positioninitialLine = $(".line").offset().top;
  $(window).scroll(function() {
    var _scroll = $(window).scrollTop();
    if(_scroll > positioninitial) {        
       if(_scroll >= (postionToTriggerMove - 5) && _scroll <= (postionToTriggerMove + 5) )
          {
              var topBarPostion = $(".line").offset().top;
              $('.line').css({'position':'absolute',"top":topBarPostion});
          }
   }
   else {
       if(_scroll >= (postionToTriggerMove - 5) && _scroll <= (postionToTriggerMove + 5) )
          {
              var topBarPostion = $(".line").offset().top;
              $('.line').css({'position':'fixed',"top":positioninitialLine});
          }

  }
  positioninitial = _scroll;
  });

});

这篇关于根据窗口滚动更改div的页边距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆