简体   繁体   English

如何在视口上固定div

[英]how to maintain div fixed on viewport

I have a fixed div on screen ( #mydiv) and is fixed at 0p x from viewport an 1000px height , my screen size is 1280 x 800 px and document height is 1600px; 我在屏幕上有一个固定的div( #mydiv)并且在视口中固定为0p x, 1000px height#mydiv) ,屏幕尺寸为1280 x 800 px,文档高度为1600px;

so I'm loosing the extra 200px from div height, how I can calculate the top position to show while Im scrolling? 所以我从div高度上损失了200px ,如何计算Im滚动时显示的顶部位置? and back to top:0 when scroll up again? 返回top:0时再次向上滚动?

If what you want is your div to be at position:0 on top of the page but still to be scrollable when you scroll down then what you are looking at is setting your div to: 如果您想要的是div位于页面顶部的位置0,但在向下滚动时仍可滚动,则您正在查看的是将div设置为:

position:absolute;
top:0;

To note that divs positioned in absolute will take their position respectivly to their closes ancestor that does not have a static position (its the value by default if you dont specify any position property for it). 要注意的是,绝对位置的div将相对于没有静态位置的关闭祖先(如果未为其指定任何位置属性,则默认为该值)将其位置作为其位置。

If by some reason you cant or dont want to have your div in absolute position, you can calculate the offset of the page and change the position of the div accordingly, assuming you are using jQuery: 如果由于某种原因您不能或不想将div放在绝对位置,则可以计算页面的偏移量,并相应地更改div的位置,并假设您使用的是jQuery:

$( window ).scroll(function() {
  $( "#mydiv" ).css({
    top: -$(document).offset().top
  })
});

This would make the div#mydiv move up and down along with the document, assuming its initial position is fixed at top:0 假定div#mydiv的初始位置固定在top:0,它将使div#mydiv与文档一起上下移动

I would really use the CSS solution (absolute position) instead of the javascript one. 我真的会使用CSS解决方案(绝对位置)而不是javascript。 Let the browser do its thing rather than setting up code that will eat resources needlessly. 让浏览器执行其任务,而不是设置将不必要地占用资源的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM