大家好,我想做一个简单的滚动分享框小部件,但它不起作用。它必须停止在特殊的div (stopscroll),但它不会停止并向下滚动,直到网页页脚。知道为什么吗?
var windw = this;
$.fn.followTo = function ( elem ) {
var $this = this,
$window = $(windw),
$bumper = $(elem),
bumperPos = $bumper.offset().top,
thisHeight = $this.outerHeight(),
setPosition = function(){
if ($window.scrollTop() <= (bumperPos - thisHeight)) {
$this.css({
position: 'absolute',
top: (bumperPos - thisHeight)
});
} else {
$this.css({
position: 'fixed',
top: 0
});
}
};
$window.resize(function()
{
bumperPos = pos.offset().top;
thisHeight = $this.outerHeight();
setPosition();
});
$window.scroll(setPosition);
setPosition();
};
$('#share_box').followTo('#stopscroll');
但是它不会在div #stopscroll上停止
css文件看起来像这样:
#share_box{
background: none repeat scroll 0% 0% #E1E1E1;
position: fixed;
width: 65px;
padding: 15px;
border-radius: 5px 0px 0px 5px;
left: 1.89%;}
任何想法?这里是jsfiddle http://jsfiddle.net/NCY6x/
你的代码中有很多语法和变量错误…
我已经更新了小提琴与一个工作和更简单的演示:http://jsfiddle.net/NCY6x/2/
$.fn.followTo = function ( elem ) {
var stopper = $(elem);
var box = this;
$(window).on("scroll resize", function(){
var x_distance = (stopper.offset().top- box.outerHeight());
if($(window).scrollTop() >= x_distance){
box.css({"position": "absolute", "top": x_distance});
} else {
box.css({"position": "fixed", "top": 0});
}
});
};
$('#share_box').followTo('#stopscroll');
嗯,在你的小提琴你没有实际加载jQuery
,然后当加载我得到一个错误说pos is not defined
,我认为是指以下行:
bumperPos = pos.offset().top;
pos
似乎没有设置在任何地方
你的脚本还有其他一些问题。查看这里的一个版本,我认为你想要的工作http://jsfiddle.net/R5z6j/1/
我删除了#stopscroll
顶部的内边距,因为它不会向下移动元素,所以顶部位置总是被设置为18px(参见控制台输出)
http://jsfiddle.net/R5z6j/5/-因为您可能实际上希望以这种方式显示