但随着用户向下滚动页面

但随着用户向下滚动页面

本文介绍了使div开始中间页面,但随着用户向下滚动页面,它仍然在顶部?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

举一个例子来说明我所描述的内容。

包含类别列表的div元素开始在页面中间,但是当用户向下滚动时,它仍然位于顶部?



我认为你在找什么。基本上你有一个相对最初定位的div,然后当页面滚动时,位置变为固定。 jQuery在这里用$(window).scroll事件进行大量的引用。



jQuery:

  var stickerTop = parseInt($('#sticker')。offset()。top); 
$(window).scroll(function(){
$(#sticker)。css((parseInt($(window).scrollTop())+ parseInt($(#sticker ).css('margin-top'))> stickerTop)?{
position:'fixed',
top:'0px'
}:{
position:'相对'
});
});

CSS: p>

  body {
width:960px;
}
#mainbar {
width:660px;
float:left;
}
#sidebar {
width:270px;
float:right;
}
#sticker {
width:200px;
padding:10px;
margin-top:25px;
背景:#eee;
border:1px solid #ccc;
}


Better to give an example, to illustrate what i am describing.

The div element with the list of categories starts mid page, but as the user scrolls down it remains at the top?

http://www.khanacademy.org/

I know how to make a fixed element. My question is how do i make the element appear by default in the center of the page, but as the user scrolls down, the element will stay at the top.

解决方案

Here's a quick jsFiddle example of what I think you're looking for. Basically you have a div that is initially positioned relative, then as the page is scrolled, the position is changed to fixed. jQuery does the heavy liting here with the $(window).scroll event.

jQuery:

var stickerTop = parseInt($('#sticker').offset().top);
$(window).scroll(function() {
    $("#sticker").css((parseInt($(window).scrollTop()) + parseInt($("#sticker").css('margin-top')) > stickerTop) ? {
        position: 'fixed',
        top: '0px'
    } : {
        position: 'relative'
    });
});​

CSS:

body {
    width: 960px;
}
#mainbar {
    width: 660px;
    float: left;
}
#sidebar {
    width: 270px;
    float: right;
}
#sticker {
    width: 200px;
    padding: 10px;
    margin-top:25px;
    background: #eee;
    border: 1px solid #ccc;
}​

这篇关于使div开始中间页面,但随着用户向下滚动页面,它仍然在顶部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 03:41