将位置更改为固定时,防止div滚动回到顶部 [英] Preventing div scrolling back to top when changing position to fixed

查看:171
本文介绍了将位置更改为固定时,防止div滚动回到顶部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个div包含一个列表的照片名称。当单击名称时,另一个div(第一个外部)与其下面的照片和注释一起显示。当第二个div滚动(使用主窗口滚动条),我不想让第一个div滚动,它应该保持在它的位置。因此,只要我打开照片div,我将第一个div的位置从绝对更改为固定。到目前为止很好,这很好。

I have a div containing a list of photo names. When a name is clicked, another div (outside the first one) is displayed with the photo and comments below it. When this second div is scrolled (using the main window scrollbar), I do not want the first div to scroll along, it should remain where it is. So, as soon as I open the photo div, I change the first div's position from absolute to fixed. So far so good, this works fine.

但是,当第一个div在照片打开之前已经滚动,这个div设置为固定,跳回到顶部,而我想要它保持在它的位置。有没有办法做到这一点?为什么会跳到顶部?

However, when the first div has been scrolled before a photo is opened, the setting of this div to fixed, causes it to jump back to the top, while I want it to remain where it was. Is there a way to do this? Why does it jump to the top?

基本上我想实现与在Facebook中显示照片相同。

Basically I want to achieve the same as showing photo's in Facebook. The background is frozen where it is while the photo area can be scrolled.

谢谢!

推荐答案

固定的div跳转到顶部,因为没有顶部/底部值基本上意味着它们位于0。

The fixed div jumps to the top because having no top/bottom values basically means they're positioned at 0.

现在,为了防止您必须将与窗口相关的当前位置(位置更改为固定

Now, to prevent this you will have to set the current position (before position is changed to fixed) in relation to the window (that's the key part).

查看我的 jsfiddle

See my jsfiddle

jquery部分:

$('#click').click(function() {
    var ftop = $('#fixer').offset().top - $(window).scrollTop();
    var fleft = $('#fixer').offset().left;
    $('#fixer').css({position: 'fixed', left: fleft + 'px', top: ftop + 'px'});
});

在位置固定之前,当前顶部坐标为[ offset计算顶部 - (窗口).scrollTop ],然后传递到 #fixer 顶部 value。 $(window).scrollTop()很重要,因为它确保 #fixer 固定。

Before the position is fixed, the current top coordinates [offset().top - (window).scrollTop] are calculated and then passed to the #fixer's top value. The $(window).scrollTop() is important because it makes sure the #fixer will always be at viewpoint when fixed.

这篇关于将位置更改为固定时,防止div滚动回到顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆