![](/img/trans.png)
[英]Detecting if an element is within the viewport by using jquery.visible.js and an offset
[英]jQuery - Detecting if element is in viewport
我正在編寫一個腳本,當它們出現在屏幕上時,它會為不同的元素提供一些動畫。
第一步是檢測它們何時進入屏幕。 但這似乎不起作用。
我嘗試了什么:
- .visible()
選擇器,我很快發現它在 jQuery 中做了其他事情。
-不同的插件,但我發現它們做的比我需要的要多,因此我決定自己寫/找一些東西。
-我當前的腳本(我在論壇的某個地方找到它並決定根據我的需要對其進行編輯)但是它有點奇怪。
$.fn.isInViewport = function () {
let elementTop = $(this).offset().top;
let elementBottom = elementTop + $(this).outerHeight();
let viewportTop = $(window).scrollTop();
let viewportBottom = viewportTop + $(window).height();
return elementBottom > viewportTop && elementTop < viewportBottom;
};
$(window).scroll(function () {
if ($('.blogcard ').isInViewport()) {
$(this).addClass("test");
console.log('success.')
} else {
console.log('No success.')
}
});
不幸的是,這似乎沒有向我的<div class='blogcard'>
添加 class 。
您對“this”的使用針對窗口而不是 .blogcard 元素:
$(window).scroll(function () {
if ($('.blogcard ').isInViewport()) {
// Use .blogcard instead of this
$('.blogcard').addClass('test');
console.log('success.')
} else {
// Remove class
$('.blogcard').removeClass('test');
console.log('No success.')
}
});
您需要將“this”上下文放入 $(window).scroll 函數中。 我通過循環元素來做到這一點,而不是僅僅檢查 .class isInViewport()
$(window).scroll(function () {
$('.blogcard').each(function(i, el){
if ($(this).isInViewport()) {
$(this).addClass('test');
console.log('content block is in viewport.', $(this))
}
})
});
刪除課程會使內容變得過多,所以我將其刪除。
請試試這個代碼...
$(window).scroll(function () { if ($('.section3 ').isInViewport()) { $('.section3').addClass('its-now-view'); alert('sction 3 is now in viewport'); } else { $('.section3').addClass('its-now-view'); alert('sction 3 is not in viewport'); } });
.section{ height:400px; } .section1{ background-color: #333; } .section2{ background-color: red; } .section3{ background-color: yellow; } .section4{ background-color: green; }
<html> <head> <title>Viewport demo</title> <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.7/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/is-in-viewport/3.0.4/isInViewport.min.js"></script> </head> <body> <div class="content-wrapper"> <div class="section section1"> <p>Content of section 1</p> </div> <div class="section section2"> <p>Content of section 2</p> </div> <div class="section section3"> <p>Content of section 3</p> </div> <div class="section section4"> <p>Content of section 4</p> </div> </div> </body> </html>
對於未來的谷歌人。 發布的 function 有一個錯誤, $(window).height()
不提供viewport
高度,而是整個文檔的高度。 這isInViewport
function 始終返回true
。 這是正確的實現:
$.fn.isInViewport = function () {
let elementTop = $(this).offset().top;
let elementBottom = elementTop + $(this).outerHeight();
let viewportTop = $(window).scrollTop();
let viewportBottom = viewportTop + window.innerHeight; // <-- here
return elementBottom > viewportTop && elementTop < viewportBottom;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.