绝对将div定位到body而不是parent

时间:2017-04-06 16:33:31

标签: javascript jquery html

我有几个孩子div,我需要绝对定位到body元素。

我不能使用position: absolute因为div不是身体的孩子。

我无法使用position: fixed,因为我需要使用div来滚动 页面。

我不能使用'.detach()or。append(element)'因为CSS级联和定位子div的方式。

我假设我可以计算出从视口到div边缘的顶部和左侧距离 - 然后将它们作为负面'top:'和'left:'应用于子div。

我不知道该怎么做。

我是否以正确的方式思考这个问题?非常感谢您的帮助和专业知识!

1 个答案:

答案 0 :(得分:1)

Not 100% sure what you are asking but my assumption is if you use a fixed position and just adjust it when the user either resizes or scrolls. Just replace the TOP_POS and LEFT_POS with where it needs to be positioned.

$(window).on('scroll resize', function() {
    $('YOUR_DIV').css({ 
    'top': TOP_POS - $(window).scrollTop(),
    'left': LEFT_POS - $(window).scrollLeft()
    });
})

If this is not what you are looking for, then please disregard.