Position a Div “Fixed” Vertically and “Absolute” Horizontally within a “Position:Relative” Container Div

后端 未结 3 1659
梦毁少年i
梦毁少年i 2020-12-19 00:42

I\'m looking for a way I can create a div which will be fixed on the page vertically, so if the user scrolls down, the div stays at the same place on the page. But have it p

相关标签:
3条回答
  • 2020-12-19 01:25

    With JQuery, use the scrollLeft() property of the document! This would work

    $(window).scroll(function(event) {
       $("#blue-box").css("margin-left", 400-$(document).scrollLeft());
    });
    

    See also

    http://jsfiddle.net/zhQkq/9/

    Good luck!

    Edit: If you want it to use your preset margin-left instead of a hard-coded "400", use

    $(window).scroll(function(event) {
       $("#blue-box").css("margin-left", $("#blue-box").css("margin-left")-$(document).scrollLeft());
    });
    
    0 讨论(0)
  • 2020-12-19 01:45

    Here's my solution (tested in Opera and Firefox): http://jsfiddle.net/cCH2Z/2 The trick is to specify right: 0px;, this will position the box 0px from the right border of the window.

    0 讨论(0)
  • 2020-12-19 01:46

    Using vanilla javascript would be something like this:

    var bb = document.getElementById('blue-box');
    window.addEventListener('scroll',function(event){
        bb.style.marginLeft = window.scrollX + 'px';
    });
    

    In modern browsers, as of 2020, you should try to use the CSS position:fixed; instead of JavaScript positioning because it is widely supported now.

    0 讨论(0)
提交回复
热议问题