让一个元素固定在页面左侧但又能上下滚动是我遇到的最困难的事情。
我已经尝试过将左侧位置更改为 $(window).scrollLeft() 的方法,但这会产生非常不稳定的动画效果。
我正在寻找的是这个 fiddle 的对立面,但我不能完全让它工作:
var leftInit = $(".scroll_fixed").offset().left;
var top = $('.scroll_fixed').offset().top - parseFloat($('.scroll_fixed').css('margin- top').replace(/auto/, 0));
$(window).scroll(function(event) {
var x = 0 - $(this).scrollLeft();
var y = $(this).scrollTop();
// whether that's below the form
if (y >= top) {
// if so, ad the fixed class
$('.scroll_fixed').addClass('fixed');
} else {
// otherwise remove it
$('.scroll_fixed').removeClass('fixed');
}
$(".scroll_fixed").offset({
left: x + leftInit
});
});
请注意,此 div 固定在顶部而不是左侧。我正在寻找相反的方向,固定在左侧而不是顶部。有什么想法吗?
我尝试编辑这个 fiddle ,但无法正常工作。
最佳答案
这个锅:
var leftInit = $(".scroll_fixed").offset().left;
var top = $('.scroll_fixed').offset().top - parseFloat($('.scroll_fixed').css('margin-top').replace(/auto/, 0));
$(window).scroll(function(event) {
var x = $(this).scrollLeft();
var y = $(this).scrollTop();
// whether that's below the form
if (x >= leftInit) {
// if so, ad the fixed class
$('.scroll_fixed').addClass('fixed');
} else {
// otherwise remove it
$('.scroll_fixed').removeClass('fixed');
}
$(".scroll_fixed").offset({
left: x + leftInit
});
});
编辑同时更改
.scroll_fixed.fixed {
position:absolute;
关于jQuery css 固定在左侧但绝对在顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16367721/