[英]Float a div within a div on scroll down and up (not on whole screen)
我在div中做了一个div,我希望内部div在外部div中上下滚动页面上下浮动。 我以某种方式设法限制不要超出外部div形式,但是当它到达底部时它会一直下到页面底部。 请帮帮我,这是我的代码css
CSS
#comment {
position: absolute;
/* just used to show how to include the margin in the effect */
}
HTML
<!--the outer div in which i have whole content -->
<div class="content">
<!--the floating div, remains well inside form top but moves down outside div from bottom -->
<div class="ftwrapper" id="comment">
</div><!--fb/twitter ends-->
</div>
JQuery的
$(function () {
var msie6 = $.browser == 'msie' && $.browser.version < 7;
if (!msie6) {
var top = $('#comment').offset().top - parseFloat($('#comment').css('margin-top').replace(/auto/, 0));
$(window).scroll(function (event) {
// what the y position of the scroll is
var y = $(this).scrollTop();
// whether that's below the form
if (y >= top) {
// if so, ad the fixed class
$('#comment').addClass('fixed');
} else {
// otherwise remove it
$('#comment').removeClass('fixed');
}
});
}
});
我根据您的要求进行了样品测试。 如果滚动太快,它不能很好地工作,但否则它可以。 我稍后会做些改动。
var prevScroll = 0;
$(window).unbind("scroll");
function reposition() {
var contPos = $("#container").offset();
var comment = $('#comment');
contPos.bottom = contPos.top + $("#container").outerHeight();
console.log('contPos',contPos);
$(window).scroll(function (event) {
// what the y position of the scroll is
var scroll = $(window).scrollTop()
, y = scroll
, pos = comment.offset()
;
pos.bottom = comment.outerHeight();
if ( scroll > prevScroll) {
//down
} else {
//up
}
prevScroll = scroll;
// whether that's below the form
console.log(pos.bottom + scroll ,":", contPos.bottom);
if (contPos.top > scroll) {
// if so, ad the fixed class
comment.css({
position: 'relative',
bottom : '0px',
left : '0px'
});
console.log("Too High");
} else if ( pos.bottom + scroll > contPos.bottom) {
//comment.removeClass('fixed');
comment.css({
position: 'absolute',
top : (contPos.bottom - comment.outerHeight() )+'px',
left : pos.left+'px'
});
console.log("Too Low");
} else {
// middle area
console.log("Perfect");
comment.css({
position: 'fixed',
top : '0px',
left : pos.left + 'px'
});
}
});
}
$(document).ready(reposition);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.