我有一个div.scroll_fixed与以下CSS
.scroll_fixed {
position:absolute
top:210px
}
.scroll_fixed.fixed {
position:fixed;
top:0;
}
Run Code Online (Sandbox Code Playgroud)
当div到达页面顶部时,我正在使用以下jQuery代码来设置.fixed类.
var top = $('.scroll_fixed').offset().top - parseFloat($('.scroll_fixed').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
$('.scroll_fixed').addClass('fixed');
} else {
// otherwise remove it
$('.scroll_fixed').removeClass('fixed');
}
});
Run Code Online (Sandbox Code Playgroud)
这适用于垂直滚动固定.但是对于一个小的浏览器窗口,水平滚动会导致与此固定div右侧的内容发生冲突.
我希望div能够水平滚动内容.
任何人都可以指出我正确的方向.还在用JS/JQuery弄湿我的脚.
我基本上希望它像本例中的第二个框一样工作.
And*_*ker 23
该演示保留了元素position:fixed
并操纵元素的 left
属性:
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
});
});
Run Code Online (Sandbox Code Playgroud)
使用leftInit
可能会考虑左边距.在这里尝试:http://jsfiddle.net/F7Bme/
big*_*dog 21
你现在可能已经开始了,但是对于寻找可水平滚动的固定元素解决方案的其他人来说,这是一个答案.创建此jquery插件是为了解决这个问题.
此演示使用购物车摘要,该摘要在固定到页面顶部时仍会水平滚动; 并且,我还使用它作为表格数据上方的标题:
演示:http://jsfiddle.net/y3qV5/434/(更新)
插件和来源:https://github.com/bigspotteddog/ScrollToFixed
用法:
$(document).ready(function() {
$('#cart').scrollToFixed( { marginTop: 10 } );
});
Run Code Online (Sandbox Code Playgroud)
使用css属性position:sticky
来获取它.
这是文章解释和现场演示.
http://updates.html5rocks.com/2012/08/Stick-your-landings-position-sticky-lands-in-WebKit
唯一的缺点是浏览器兼容性.