How to turn off JS/CSS background effect on scroll?

扶醉桌前 提交于 2019-12-13 06:37:28

问题


I love cool JS/CSS background effects, but on many slower devices they take up a lot of CPU usage and really bog down the browser. A really good example is this site: http://volar.makwan.net/index02.html

The code in the HTML for this effect is <div id="fss" class="fss full-screen "></div> - is there a way to disable this DIV when the user trolls away from #home so resources aren't dedicated to the background effect when it isn't visible?


回答1:


You can remove the class (or id) of the div which is causing the resource drain when the div leaves the viewport (ie the screen). You can even add a temporary class while it is off the screen if you wish.

Take a look at the code snippet below. Although you can't see it, the green box loses the class green when it goes off the screen, and gets the class orange added to it instead (inspect the element to see it change). Then when it comes back onto the screen the div gets the class green and loses the class orange:

function isElementInViewport(el) {
    let rect = el.getBoundingClientRect();
    return rect.bottom > 0 && rect.right > 0 && rect.left < (window.innerWidth || document.documentElement.clientWidth) && rect.top < (window.innerHeight || document.documentElement.clientHeight);
}

let isVisible = true;

window.onscroll = function() {
  let myGreenBox = document.getElementById('green-box');
  if(!isElementInViewport(myGreenBox) && isVisible) {
    myGreenBox.classList.add("orange");
    myGreenBox.classList.remove("green");
    
    console.log("Green Box style removed");
    isVisible = false;
  } else if(isElementInViewport(myGreenBox) && !isVisible){
    myGreenBox.classList.add("green");
    myGreenBox.classList.remove("orange");
    console.log("Green Box style added");
    isVisible = true;
  }
  
};
.box {
  height: 100px;
  width: 100px;
}

.green {
  background-color: lime;
}

.orange {
  background-color: orange;
}

.container {
  height: 200vh;
}
<div class="container">
  <div id="green-box" class="box green">

  </div>
</div>

You can apply this idea to <div id="fss" class="fss full-screen "></div> to 'disable' it when it is off the screen.



来源:https://stackoverflow.com/questions/52532774/how-to-turn-off-js-css-background-effect-on-scroll

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!