亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

當用戶滾動到特定元素時觸發事件-使用jQuery

當用戶滾動到特定元素時觸發事件-使用jQuery

慕斯709654 2019-07-15 16:10:35
當用戶滾動到特定元素時觸發事件-使用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個贊

把這個問題和最好的答案結合在一起當用戶滾動通過頁面的某一部分時,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-07-15
  • 3 回答
  • 0 關注
  • 1136 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號