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

寵の児 提交于 2019-12-01 16:53:33

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());
});

To link a #blue-box element to the horizontal scroll of a window 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';
});

If it had a margin originally defined in px, don't forget to trim off the 'px' from the end of the string, and then convert the text to an int prior to adding the window.scrollX offset. Then put the 'px' back on the end. Functions like String.replace() and parseInt() would help with that.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!