使用水平滚动将潜水位置从绝对更改为固定

Change Div Position from Absolute to Fixed with Horizontal Scroll

本文关键字:水平 滚动 位置 潜水      更新时间:2023-09-26

我有一个网站,它使用水平滚动插件在https://github.com/brandonaaron/jquery-mousewheel.没有问题。

我的问题是,我有一个250像素宽、100%高的div,从屏幕右侧开始100像素。当我滚动(水平)时,div向左滚动,最终从屏幕上消失。div的"位置"设置为"绝对"。我想要的是,一旦div到达浏览器窗口的左侧,div就固定在屏幕的左侧。

我猜,一旦div到达屏幕上的某个特定位置(最左边),我就需要使用JS来更改它的CSS。我见过不少网站通过垂直滚动实现这一点,菜单栏一旦到达屏幕顶部,就会固定在屏幕顶部。菜单可能在页面下方的一半开始,然后在滚动时向上移动。我只是想在水平面上达到同样的效果。

一般来说,我对代码比较陌生,对Javascript来说也是全新的。我可能吃得太多了,但我喜欢挑战。感谢任何人的帮助。

我要更改的CSS代码是

#header {
    width: 250px;
    background: rgba(22,22,22,.85);
    height: 100%;
    position: absolute;
    margin-left: calc(100% - 350px);
    z-index: 999;
}

然后更改为

#header {
    width: 250px;
    background: rgba(22,22,22,.85);
    height: 100%;
    position: fixed;
    margin-left: 0px;
    z-index: 999;
}

这是我根据你的问题理解所做的尝试。。是的,我有用户javascript。。

HTML:

<div id="headerSlideContainer">
    <div id="headerSlideContent">
        Header content goes here!
    </div>
    <div id="new">
        Other Contents
    </div>
</div>

CSS:

#headerSlideContainer {
    position: absolute;
    top:0px;
    width: 100%;
   height:1000px;
    background: black;
}
#headerSlideContent {
    width: 250px;
    background-color:red;
    height: 100%;
    position: fixed;
    margin-left: 0px;
    z-index: 999;
}
#new{
    top:60px;
    z-index:2;
    height:100px;
    background:Orange;
    position:absolute;
    color: white;
}

和js:

$(function() {
    var bar = $('#headerSlideContainer');
    var top = bar.css('top');
    $(window).scroll(function() {
        if($(this).scrollright() > 100) {
            bar.stop().animate({'top' : '5px'}, 500);
        } else {
            bar.stop().animate({'top' : top}, 500);
        }
    });
});

根据需要更改滚动权限的数量。。如果scrollright不起作用,请尝试scrollleft()。。如果你有任何问题,请告诉我。。

这里有一篇文章解释了如何垂直地做到这一点,但同样的概念也应该适用于您的情况。

教程:http://jqueryfordesigners.com/fixed-floating-elements/

演示:http://jqueryfordesigners.com/demo/fixedfloat.html