相对于窗口的位置

新手上路,请多包涵

我有一个 Tumblr 帐户,我正在编辑它的 html。我的问题是:如何让我的侧边栏处于某个位置,然后我在页面上向下滚动,它停留在相对于我的浏览器的位置?有关我正在谈论的示例,请单击“提问”并查看“类似问题”,然后滚动。我更希望它在 CSS 中。我已经尝试了我能想到的一切。

原文由 judh1234 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 244
2 个回答

set the elements css position attribute to fixed and user top / left and margin to place it where you想要它是。像这样:

 #sideBar {
    position: fixed;
    display: block;
    top: 50%;
    left: 10px;
    margin: -100px 0 0 0;
    height: 200px;
    width: 50px;
}

上面的代码将垂直居中 200px 高 div 并将其放置在 10px 从左手边。

更新

此示例将向您展示如何实现您的目标! 用 jquery 演示

更新 (1)

下面的 jquery 代码可能是最快的方式来实现你想要的,对其他 html/css 的更改最少。只需将以下代码粘贴到 文档就绪 函数中,并如下所述更改几位 css。

 $(window).scroll(function(){
    if($(window).scrollTop() >= 200){
        $('anchor3').css({
            "margin-top": "80px"
        })
        $('icon').css({
            "margin-top": "10px"
        })
        $('oldurl').css({
            "margin-top": "296px"
        })
    }
    else{
        $('anchor3').css({
            "margin-top": 300 - $(window).scrollTop()
        })
        $('icon').css({
            "margin-top": 230 - $(window).scrollTop()
        })
        $('oldurl').css({
            "margin-top": 516 - $(window).scrollTop()
        })
    }
})

You need to change the CSS for a3text to make margin-top:60px , remove the position and margin-left attributes, then add display: block

Ideally, you would just have icon , anchor3 , and oldurl inside one container div so that you could just use jquery on the container而不是单独的三个项目!

但这应该让你得到你想要的东西(在 FF Scratchpad 的实时 tumblr 网站上测试)。

更新 (2)

启动 firefox 并转到页面: http ://thatoneguyoveryonder.tumblr.com/ 然后打开暂存器 (SHIFT + F4) 复制/粘贴以下代码并按 CTRL+L。然后它应该说一些东西(在暂存器中),比如 /* [object Object] */ 如果发生这种情况,请向下滚动网页并观看魔术发生 - 如果这是你想要的,我会为你解释实现它:)

 $('#sidebar').css({
    position:'fixed',
    top:410,
    left:700 + 60 + (($(window).width()-940) / 2),
    "z-index":900
});

$(window).scroll(function(){
    if($(window).scrollTop() >= 370){
        $('#sidebar').css({
            top: '30px'
        })
    }
    else{
        $('#sidebar').css({
            top: 410 - $(window).scrollTop()
        })
    }
})

原文由 Steven 发布,翻译遵循 CC BY-SA 3.0 许可协议

您可以使用

position:fixed

这是同一个 http://jsfiddle.net/aBaNM/ 的 jsfiddle,即使您滚动正文,红色 div 也应该放置在那里。

原文由 sublime 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题