当用户滚动到特定元素时触发事件-使用jQuery我有一个H1,很远的一页.。<h1 id="scroll-to">TRIGGER EVENT WHEN SCROLLED TO.</h1>当用户滚动到h1时,或者在浏览器的视图中,我想触发一个警告。$('#scroll-to').scroll(function() {
alert('you have scrolled to the h1!');});我该怎么做?
3 回答
饮歌长啸
TA贡献1951条经验 获得超3个赞
var element_position = $('#scroll-to').offset().top;$(window).on('scroll', function() {
var y_scroll_pos = window.pageYOffset;
var scroll_pos_test = element_position;
if(y_scroll_pos > scroll_pos_test) {
//do stuff
}});更新
var element_position = $('#scroll-to').offset().top;var screen_height = $(window).height();var activation_offset = 0.5;
//determines how far up the the page the element needs to be before triggering the functionvar
activation_point = element_position - (screen_height * activation_offset);var max_scroll_height = $('body').height() - screen_height - 5;
//-5 for a little bit of buffer//Does something when user scrolls to it OR//Does it when user has reached the bottom
of the page and hasn't triggered the function yet$(window).on('scroll', function() {
var y_scroll_pos = window.pageYOffset;
var element_in_view = y_scroll_pos > activation_point;
var has_reached_bottom_of_page = max_scroll_height <= y_scroll_pos && !element_in_view;
if(element_in_view || has_reached_bottom_of_page) {
//Do something
}});添加回答
举报
0/150
提交
取消
