第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

請問當用戶滾動到特定元素時觸發(fā)事件-使用jQuery

請問當用戶滾動到特定元素時觸發(fā)事件-使用jQuery

不負相思意 2019-10-20 16:12:47
當用戶滾動到特定元素時觸發(fā)事件-使用jQuery我有一個H1,很遠的一頁.。<h1 id="scroll-to">TRIGGER EVENT WHEN SCROLLED TO.</h1>當用戶滾動到h1時,或者在瀏覽器的視圖中,我想觸發(fā)一個警告。$('#scroll-to').scroll(function() {      alert('you have scrolled to the h1!');});我該怎么做?
查看完整描述

3 回答

?
長風秋雁

TA貢獻1757條經(jīng)驗 獲得超7個贊

把這個問題和最好的答案結(jié)合在一起當用戶滾動通過頁面的某一部分時,jQuery觸發(fā)操作

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

更新

我已經(jīng)改進了代碼,以便當元素位于屏幕的一半而不是頂部時觸發(fā)。如果用戶點擊屏幕底部,并且該函數(shù)尚未啟動,它也將觸發(fā)代碼。

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



查看完整回答
反對 回復(fù) 2019-10-21
  • 3 回答
  • 0 關(guān)注
  • 369 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號