问题描述
我有一个div.scroll_fixed与下列CSS
.scroll_fixed {
position:absolute
top:210px
}
.scroll_fixed.fixed {
position:fixed;
top:0;
}
我使用下面的jQuery代码来设置.fixed类div到达页面的顶部。
var top = $('。scroll_fixed')。offset()。top - parseFloat ($('。scroll_fixed')。css('margin-top')。replace(/ auto /,0));
$(window).scroll(function(event){
//滚动的y位置是
var y = $(this).scrollTop
//是否低于表单
if(y> = top){
//如果是这样,ad是固定类
$('。scroll_fixed ').addClass('fixed');
} else {
//否则删除它
$('。scroll_fixed'
});
这对于垂直滚动修正非常有用。但是使用小的浏览器窗口,水平滚动会导致与此固定div右边的内容发生冲突。
我希望div与内容水平滚动。 / p>
任何人都可能指向正确的方向。仍然让我的脚潮湿与JS / JQuery。
我基本上希望它像第二个框在这。
demo保持元素的 position:fixed
并操作元素的左
属性:
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();
//是否低于
形式if(y> = top){
//如果是, b $ b $('。scroll_fixed')。addClass('fixed');
} else {
// else remove it
$('。scroll_fixed')。removeClass ');
}
$(。scroll_fixed)。offset({
left:x + leftInit
});
$ b b});
使用 leftInit
帐户。尝试一下:
I have a div.scroll_fixed with the following CSS
.scroll_fixed {
position:absolute
top:210px
}
.scroll_fixed.fixed {
position:fixed;
top:0;
}
I'm using the following jQuery code to set the .fixed class when the div reaches the top of the page.
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');
}
});
This works great for the vertical scroll fixing. But with a small browser window, horizontal scrolling causes a clash with content to the right of this fixed div.
I would like the div to scroll with the content horizontally.
Could anyone point me in the right direction. Still getting my feet wet with JS/JQuery.
I basically want it to work like the second box in this example.
The demo is keeping the element's position:fixed
and manipulating the left
property of the element:
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
});
});
Using leftInit
takes a possible left margin into account. Try it out here: http://jsfiddle.net/F7Bme/
这篇关于如何获得固定位置div与内容水平滚动?使用jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!