我可以保持一个DIV总是在屏幕上,但不总是在一个固定的位置? [英] Can I keep a DIV always on the screen, but not always in a fixed position?

查看:221
本文介绍了我可以保持一个DIV总是在屏幕上,但不总是在一个固定的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个主窗体为我的网站,我想把一个div停靠在主窗体内部区域的顶部。尽管滚动位置,此div应始终可见。这是否可能?

I have a master form for my website, and I want to dock a div to the top of the content area inside the master form. This div should always be visible despite scroll position. Is this possible?

一张照片会更好地解释它。

A picture would explain it better.

推荐答案

a href =http://jsfiddle.net/YpKTP/>示例作为注释,所以我想我会写出一个完整的答案。

I posted a sample as a comment, so I suppose I'll write out a full answer to this.

标记非常简单,但每个部分都有一些重要的注释。

The markup is pretty straight-forward, but there are some important notes for each section.

<div id="page">
    <div id="header">
        <div id="header-inner"> <!-- Note #1 -->
            <img src="http://placehold.it/300x100" />
        </div>
    </div>
    <div id="content">
        <!-- Some Content Here -->
    </div>
</div>



CSS



CSS

#page {
    padding: 100px;
    width: 300px;
}

#header,
#header-inner { /* Note #1 */
    height: 100px;
    width: 300px;
}

.scrolling { /* Note #2 */
    position: fixed;
    top: 0;
}



JavaScript



JavaScript

//jQuery used for simplicity
$(window).scroll(function(){
  $('#header-inner').toggleClass('scrolling', $(window).scrollTop() > $('#header').offset().top);

  //can be rewritten long form as:
  var scrollPosition, headerOffset, isScrolling;
  scrollPosition = $(window).scrollTop();
  headerOffset = $('#header').offset().top;
  isScrolling = scrollPosition > headerOffset;
  $('#header-inner').toggleClass('scrolling', isScrolling);
});



注意#1



滚动标题将使用 position:fixed 附加到页面的顶部,但是此样式将从内容流中删除内容,这将导致内容跳转,除非其容器保持

Note #1

The scrolling header will be attached to the top of the page using position: fixed, but this style will remove the content from content flow, which will cause the content to jump unless its container maintains the original height.

样式属于CSS,但可能难以正确对齐元素与其原始位置。您可能需要通过JavaScript动态设置 css属性。

Styles belong in CSS, however it may be difficult to properly align some elements with their original position. You may need to dynamically set the left or right css property via JavaScript.

这篇关于我可以保持一个DIV总是在屏幕上,但不总是在一个固定的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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