在视口中更改类

时间:2019-02-11 23:51:09

标签: javascript html

我不是Java语言的英雄。 有没有人可以帮助我?

我找到了此代码,我想将其更改为更改所有部分(或p,div 、?)的纯JavaScript代码

请参见下面的代码

喜欢https://codepen.io/josephyoung83/pen/bNvpdR

但是我讨厌jquery并且喜欢我可以轻松实现到任何站点的简约代码。

谢谢!

// The checker
const gambitGalleryIsInView = el => {
	const scroll = window.scrollY || window.pageYOffset
	const boundsTop = el.getBoundingClientRect().top + scroll
	
	const viewport = {
		top: scroll,
		bottom: scroll + window.innerHeight,
	}
	
    const bounds = {
		top: boundsTop,
		bottom: boundsTop + el.clientHeight,
	}
	
	return ( bounds.bottom >= viewport.top && bounds.bottom <= viewport.bottom ) 
		|| ( bounds.top <= viewport.bottom && bounds.top >= viewport.top );
}


// Usage.
document.addEventListener( 'DOMContentLoaded', () => {
	const tester = document.querySelector( '.tester' )
	const answer = document.querySelector( '.answer' )
	
	const handler = () => raf( () => {
		answer.innerHTML = 'Is the div visible? ' + ( gambitGalleryIsInView( tester ) ? 'Yes' : 'No' )
	} )
	
	handler()
	window.addEventListener( 'scroll', handler )
} )

// requestAnimationFrame
const raf = 
    window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    function( callback ) {
        window.setTimeout( callback, 1000 / 60 )
    }
*{
  font-family:arial;
}


.answer{
position:fixed;
top:0;
font-size:30px;
padding:20px;
}


.tester{ 
  position:absolute;
  top:2000px;
  padding:40px;
  background:red;
  color:white;
  margin-bottom:2000px
  }
<div class='tester'>Am I in the view?</div>
<div class='answer'>Is the div visible? No</div>

0 个答案:

没有答案