我正试着在我的网站上运行这个脚本。当id在viewport中时,它会触发警报。问题是,当id在视区中时,警报一直在运行。不能让它只运行一次。我怎么能这样做呢?
function inViewport( element ){
// Get the elements position relative to the viewport
var bb = element.getBoundingClientRect();
// Check if the element is outside the viewport
// Then invert the returned value because you want to know the opposite
return !(bb.top > innerHeight || bb.bottom < 0);
}
var myElement = document.querySelector( 'holaTest' );
// Listen for the scroll event
document.addEventListener( 'scroll', event => {
// Check the viewport status
if( inViewport( myElement ) ){
alert('hello there')
}
})发布于 2020-05-01 02:00:51
除了Andre的回答,当警报出现在视口上时,您只能检查警报一次。这样,每次元素位于视口中时,它都会发出一次警报:
function inViewport( element ){
// Get the elements position relative to the viewport
var bb = element.getBoundingClientRect();
// Check if the element is outside the viewport
// Then invert the returned value because you want to know the opposite
return !(bb.top > innerHeight || bb.bottom < 0);
}
var myElement = document.querySelector( '.holaTest' );
// Listen for the scroll event
var t = true;
document.addEventListener( 'scroll', event => {
// Check the viewport status
if( inViewport( myElement ) && t){
alert('hello there');
console.log("try");
t = false;
}
if (!inViewport(myElement)) {
t = true;
}
})
https://stackoverflow.com/questions/61529640
复制相似问题