瓒呭嚘鐞嗐亴杌姐亜JavaScript銈广偗銉兗銉垽瀹氥伄CSS銈€儖銉°兗銈枫儳銉充綔鎴愭柟娉

銈广偗銉兗銉垽瀹氥伄浣滄垚鏂规硶

浣滄垚銇椼仧銈点兂銉椼儷銇亾銇°倝

涓鑸殑銇壒瀹氥伄瑕佺礌銇俱仹銈广偗銉兗銉仐銇熴倝CSS銇產ctive銈儵銈广倰浠樸亼銇SS銈€儖銉°兗銈枫儳銉炽倰瀹熻銇欍倠鍫村悎銆丣avaScript銇畇croll銈ゃ儥銉炽儓銇屼娇鐢ㄣ仌銈屻倠銇屻scroll銈ゃ儥銉炽儓銈掍娇鐢ㄣ仚銈嬨仺鍑︾悊銇岄噸銇忋仾銈嬨仺銇勩亞鍟忛銇屻亗銈嬨

銇俱仧銆佺壒瀹氥伄瑕佺礌銇欍伖銇︺伀active銈儵銈广倰浠樸亼銇SS銈€儖銉°兗銈枫儳銉炽倰瀹熻銇欍倠瑕佺礌銇屻仾銇忋仾銇c仸銈scroll銈ゃ儥銉炽儓銈掑疅琛屻仐缍氥亼銇︺亜銈媁eb銈点偆銉堛亴澶氥亸瀛樺湪銇欍倠銆

IntersectionObserver銈掍娇鐢ㄣ仚銈

scroll銈ゃ儥銉炽儓銇с伅銇亸IntersectionObserver銈掍娇鐢ㄣ仚銈嬨仺鍑︾悊銇岃唤銇忋仾銈嬨

IntersectionObserver銇ㄣ伅銈裤兗銈层儍銉堛仺銇倠瑕佺礌銈掔洠瑕栥仚銈嬨仧銈併伄API銇ц┏绱般伅MDN銇甒eb銈点偆銉銇浉銇嬨倢銇︺亜銈嬨亴銆佸唴瀹广亴灏戙仐闆c仐銇勩伄銇ф渶鍒濄伅銈裤兗銈层儍銉堛仺銇倠瑕佺礌銇俱仹銈广偗銉兗銉仌銈屻仧銇嬪垽瀹氥仹銇嶃倠API銇犮仺瑾嶈瓨銇с亶銈屻伆鑹亜銇с仚銆

IntersectionObserver銈掍娇鐢ㄣ仐銇熴偝銉笺儔

銇俱仛JavaScript銇墠銇獺TML銇–SS銈掔敤鎰忋仚銈嬨

浠ヤ笅銇偟銉炽儣銉仹銇.scrollAnime銇绱犮伨銇с偣銈儹銉笺儷銇曘倢銇熼殯銇.active銇岃拷鍔犮仌銈屻仧鍫村悎銇疌SS銈€儖銉°兗銈枫儳銉炽亴鍕曚綔銇欍倠銈堛亞銇仐銇熴

<h1>IntersectionObserver銇倛銈嬨偣銈儹銉笺儷浣嶇疆鍙栧緱</h1>
<h2>鈫 1000px浠ヤ笂銈广偗銉兗銉仐銇︾⒑瑾嶃仐銇︺伩銇︺亸銇犮仌銇勩</h2>
<div class="scrollAnime">scrollAnime1</div>
<hr>
<div class="scrollAnime">scrollAnime2</div>
h2, hr {
  margin-bottom: 1000px;
}
.scrollAnime {
  transition: all 1s linear;
  transform: translateX(-20px);
  opacity: 0;
}
.scrollAnime.active {
  transform: translateX(0);
  opacity: 1;
}

JavaScript銇互涓嬨伄閫氥倞銆俼uerySelectorAll銇SS銈€儖銉°兗銈枫儳銉炽倰鍕曚綔銇曘仜銈嬭绱犮倰鍙栧緱銇欍倠銆

銇欍伖銇︺伄瑕佺礌銇.active銇岃拷鍔犮仌銈屻仧鍫村悎銇痮bserver.disconnect()銇х祩浜嗐仌銈屻倠銇熴倎銆scroll銈ゃ儥銉炽儓銇犮亼銇嚘鐞嗐仺銇仌銇凧avaScript銇屽嫊浣溿仐銇ゃ仴銇戙倠銇撱仺銇屻仾銇勩

const targets = [].slice.call(document.querySelectorAll('.scrollAnime'))
const targetsLen = targets.length
if (targetsLen) {
  const observer = new IntersectionObserver(changes => {
    for (let i in changes) {
      if (changes[i].isIntersecting) {
        changes[i].target.classList.add('active')
        const activeLen = document.querySelectorAll('.scrollAnime.active').length
        if (targetsLen === activeLen) {
          observer.disconnect()
        }
      }
    }
  })
  targets.forEach(target => observer.observe(target))
}

銇°仾銇裤伀IntersectionObserver銇疘E11銇娇鐢ㄤ笉鍙伄銇熴倎銆IE11銈傚璞°伄Web銈点偆銉堛伄鍫村悎銇痯olyfill.min.js銈掕銇胯炯銈撱仹銇忋仩銇曘亜銆

polyfill.min.js銈掕銇胯炯銈併伆IE11銇с倐鍕曚綔銇椼伨銇欍

<script src="https://polyfill.io/v2/polyfill.min.js?features=IntersectionObserver"></script>

IntersectionObserver銇倛銈嬨偣銈儹銉笺儷鍒ゅ畾CSS銈€儖銉°兗銈枫儳銉炽偟銉炽儣銉