首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >只运行一次javascript函数

只运行一次javascript函数
EN

Stack Overflow用户
提问于 2020-05-01 01:48:09
回答 2查看 36关注 0票数 0

我正试着在我的网站上运行这个脚本。当id在viewport中时,它会触发警报。问题是,当id在视区中时,警报一直在运行。不能让它只运行一次。我怎么能这样做呢?

代码语言:javascript
复制
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')
  }
})
EN

Stack Overflow用户

发布于 2020-05-01 02:00:51

除了Andre的回答,当警报出现在视口上时,您只能检查警报一次。这样,每次元素位于视口中时,它都会发出一次警报:

代码语言:javascript
复制
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;
  }
})

票数 0
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61529640

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档