我正在使用 Javascript 代码 .offset.top
来修复一个元素,但我想在到达另一个元素时结束它。
<script>
$(document).ready(function (){
var sidebartop = $('.single-content').offset().top;
$(window).scroll(function (event){
var y = $(this).scrollTop();
if ( y>= sidebartop ){
$('#sharing-links').addClass('fixed');
} else {
$('#sharing-links').removeClass('fixed');
}
});
});
</script>
这是html
<div id="sharing-links">
<!-- this is the fixed element -->
</div>
<div class="single-content">
<!-- when the div reaches here is adds the .fixed -->
<div class="div2">
<!-- I want the fixed element to end when it reaches this div -->
</div>
</div>
有人知道怎么解决吗?
最佳答案
有很多关于这个主题的相关问题,你会发现很多技巧,有些有效,有些不太好,但是当滚动固定时,我总是使用这个 jquery 插件,旨在解决这个确切的问题。
演示:
http://jsfiddle.net/ZczEt/167/ http://jsfiddle.net/y3qV5/434/ http://jsfiddle.net/k2R3G/81/
插件和源代码
https://github.com/bigspotteddog/ScrollToFixed
用法:
$(document).ready(function() {
$('#mydiv').scrollToFixed();
});
编辑:
如果您只是在寻找那一行,您应该使用它来计算 .single-content
顶部。
$(document).ready(function (){
var auxtop = $('.single-content').offset().top
var margintop = parseFloat($('.single-content').css('margin-top').replace(/auto/, 0));
var sidebartop = auxtop - margintop;
$(window).scroll(function (event){
var y = $(this).scrollTop();
if ( y>= sidebartop ){
$('#sharing-links').addClass('fixed');
} else {
$('#sharing-links').removeClass('fixed');
}
});
});
关于javascript - 如何使用 .offset.top 结束固定元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19872216/