【问题标题】:Sidebar to scroll down/up as user scroll down/up the browser window without using position: sticky and fixed?当用户向下/向上滚动浏览器窗口而不使用位置时,侧边栏向下/向上滚动:粘性和固定?
【发布时间】:2019-12-22 07:44:51
【问题描述】:

当我们向下滚动时,我需要侧边栏向下滚动,我不能使用 CSS 位置 - 固定/粘性,因为侧边栏水平位置需要与放大和缩小的表单一致,并且应该适用于 chrome 和 IE11,但是我使用的是相对位置和绝对位置。 当我们通过使用 getBoundingClientRect() 函数计算窗体在视口上方的位置向下滚动时,我尝试使用逻辑来修改侧边栏的顶部属性(位置:绝对),但是侧边栏从一个位置到另一个位置的过渡并不平滑并且给出了糟糕的用户体验。 需要有一些逻辑可以平滑地改变侧边栏的位置并将其向上/向下 aImage of sidebar with viewports 我们向上/向下滚动。

【问题讨论】:

  • 您能否发布Minimal, Reproducible Example,以便我们了解您所尝试的现在效果如何?
  • 我已经完成了这项工作,并在下面的答案中提供了解决方案。谢谢!

标签: javascript html css scroll position


【解决方案1】:

我让他的工作结合了相对定位和固定定位。 position: relative 当用户滚动小于 250px 并且如果用户滚动大于 250px 则 position 属性更改为 fixed 与 top: 150px 而不提供 right/left 属性。解决方案的关键是不提供 right/left 属性,这会导致侧边栏的水平位置与放大/缩小时的表单位置保持一致,方法是保持侧边栏相对于其自身初始位置的水平位置。 早些时候,我提供了 right 属性以及 top 和 position: fixed。放大时,右:50px 属性导致侧边栏逐渐远离窗体并靠近视口的右边缘,使其看起来很奇怪。

根据 (Position fixed without top and bottom) 的答案 – “使用固定位置而不设置顶部、左侧、.. 将具有与相对于其自身初始位置的绝对位置相同的行为。但是设置 top, left, ... 将固定相对于文档或页面的位置。”

//sidebar.js
handleSidebarScroll() {
$(document).scroll(function() {
    let scrollTop = $(window).scrollTop;
    let sidebar = $('.sidebar');
    if(scrollTop < 250 ) { 
        If(sidebar.hasClass('sticky-sidebar-bottom')){
        sidebar.removeClass('sticky-sidebar-bottom');
    }
    sidebar.addClass('sticky-sidebar-top');
  }
    else {
        if(sidebar.hasClass('sticky-sidebar-top')){
        sidebar.removeClass('sticky-sidebar-top');
    }
   sidebar.addClass('sticky-sidebar-bottom');
    }
}

//SCSS
.sidebar-container{
    position: relative;
    }
.sidebar {
    width: 200px;
    height: 65vh;
    border: 5px solid black;
    &.sidebar-sticky-top{
        position: absolute;
        top: 50px;
        }
    &.sidebar-sticky-bottom{
        position: fixed;
        top: 150px;
        }
}

对于那些刚接触 scss 的人 - “&.sidebar-sticky-top” 是选择具有两个类的元素 - “sidebar” 和 “sidebar-sticky-top” 。 &。是父选择器并引用外部选择器(本例中为“.sidebar”)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-06
    • 1970-01-01
    • 1970-01-01
    • 2015-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-17
    相关资源
    最近更新 更多