为了账号安全,请及时绑定邮箱和手机立即绑定

请问当用户滚动到特定元素时触发事件-使用jQuery

请问当用户滚动到特定元素时触发事件-使用jQuery

人到中年有点甜 2019-10-21 16:12:04
当用户滚动到特定元素时触发事件-使用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 回答

?
慕的地8271018

TA贡献1796条经验 获得超4个赞

把这个问题和最好的答案结合在一起当用户滚动通过页面的某一部分时,jQuery触发操作

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
    }});



查看完整回答
反对 回复 2019-10-22
  • 3 回答
  • 0 关注
  • 426 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信