js如何實現元素曝光上報

js如何實現元素曝光上報

?更新時間:2019年08月07日 15:34:29 ? 作者:rbin ?

這篇文章主要介紹了js如何實現元素曝光上報,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

進行數據上報的時候,經常會遇到列表數據曝光上報的問題,只對在當前可視范圍內的數據內容進行曝光上報,而對于未在可視范圍內的數據不進行曝光上報,等待用戶滾動頁面或者區域使元素出現在可視范圍內時才進行曝光上報。

解決方案

目前針對此類問題,主要有兩種解決方案。

方案一:監聽頁面或者區域scroll事件,通過getBoundingClientRect接口取元素的位置與可視窗口進行判斷。


functionisElementInViewport(el) {

??varrect = el.getBoundingClientRect();


??varwidth_st = rect.width / 2,

????height_st = rect.height / 2;


??varinnerHeight = window.innerHeight,

????innerWidth = window.innerWidth;



??if(? rect.top <=0 && rect.height > innerHeight

????|| rect.left <= 0 && rect.width > innerWidth

??) {

????returnrect.left * rect.right <= 0

??????|| rect.top * rect.bottom <= 0

??}


??return(

??????rect.height > 0

????&& rect.width > 0

????&& ( ( rect.top >= 0 && rect.top <= innerHeight - height_st )

??????|| ( rect.bottom >= height_st && rect.bottom <= innerHeight ) )

????&& ( ( rect.left >= 0 && rect.left <= innerWidth - width_st )

??????|| ( rect.right >= width_st && rect.right <= innerWidth ) )

??);

}


varnodes = document.querySelectorAll(".item")

functionreport(node) {

??// 上報的邏輯

}

window.onscroll = function() {

??nodes.forEach(node => {

????if( isElementInViewport(node) ) {

??????report(node)

????}

??})


}

優點:兼容性好

缺點:

需要關注頁面或者區域的scroll事件

頻繁的scroll事件,性能問題

方案二:通過 IntersectionObserver 監聽元素是否處于可視范圍


functionreport(node) {

??// 上報的邏輯

}

varintersectionObserver = newIntersectionObserver(entries => {

??entries.forEach(entry => {

????if( entry.intersectionRatio > 0 ) {

??????report(entry.target)

????}

??})

})

varnodes = document.querySelectorAll(".item")

nodes.forEach(node => {

??intersectionObserver.observe(node)

})

原文:js如何實現元素曝光上報_javascript技巧_腳本之家 (jb51.net)

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容