当元素滚动经过页面顶部时动态更改元素值
我有一个按日期排序的项目列表,我希望当用户滚动经过元素时日期保持固定在侧面,以便用户始终知道元素的日期。
我的 html 看起来像这样:
<div class="event_date">Jan 1, 2012</div>
<div> stuff here </div>
<div> stuff here </div>
<div class="event_date">Jan 2, 2012</div>
<div> stuff here </div>
<div> stuff here </div>
<div class="event_date">Jan 3, 2012</div>
<div> stuff here </div>
...
我已经有一个固定的 div 框,当用户在页面上滚动时它不会移动
<div id="current_date_box"></div>
我当前的 Javascript 看起来像这样:
$(window).scroll(function(){
if ($(".event_date").offset().top < $(window).scrollTop()) {
//the code only affects the first element with class event_date
var selected_date = $(".event_date).html();
$("#current_date_box").html(selected_date);
}
});
滚动工作正常,我可以在滚动时更改数据,但是,问题是,因为我使用类选择器,它总是只选择类列表中的第一个元素。我不确定如何让它与页面上的每个类元素一起工作,并且我无法为它们提供每个唯一的 ID,因为假设可能有无限的数量,因为它是从日历数据库中提取的,我认为这是不切实际的。
我也尝试让它与 eq[i] 等一起工作,但我也无法弄清楚。我还尝试了使用 $(this)
的各种方法,但没有效果,但也许我实施错误。
我想我必须按照
$(".event_date").offset().change() do something
But offset().change()
isn't support 做一些事情。
任何帮助将不胜感激!
I have a list of items sorted by the date, I want the date to remain fixed on the side as the user scrolls past the elements so that the user always knows the dates of the elements.
My html looks something like this:
<div class="event_date">Jan 1, 2012</div>
<div> stuff here </div>
<div> stuff here </div>
<div class="event_date">Jan 2, 2012</div>
<div> stuff here </div>
<div> stuff here </div>
<div class="event_date">Jan 3, 2012</div>
<div> stuff here </div>
...
I already have a fixed div box that doesn't move when the user scrolls on the page
<div id="current_date_box"></div>
My current Javascript looks like this:
$(window).scroll(function(){
if ($(".event_date").offset().top < $(window).scrollTop()) {
//the code only affects the first element with class event_date
var selected_date = $(".event_date).html();
$("#current_date_box").html(selected_date);
}
});
The scroll works fine and I can get the data to change on scroll however, the problem is that because I'm using a class selector, it always only selects the first element from the list of classes. I'm not sure how to get it to work with every class element on the page and I can't give them each unique IDs because there could hypothetically be an infinite amount because it's pulled from a calendar DB and that's just not practical I think.
I've also tried to get it work with eq[i]
etc and I can't figure it out either. I've also tried various methods of using $(this)
with no avail but maybe I'm implementing it wrong.
I think I have to do something along the lines of
$(".event_date").offset().change() do something
But offset().change()
isn't supported.
Any help would be appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
类选择器应该返回所有匹配元素的集合。但我认为你必须将它包装在每个函数中......
The class selector should return a collection of all matched elements. But you must wrap it in an each function, I think...