如何关闭滚动上的JS / CSS背景效果? [英] How to turn off JS/CSS background effect on scroll?

查看:133
本文介绍了如何关闭滚动上的JS / CSS背景效果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢炫酷的JS / CSS背景效果,但是在许多速度较慢的设备上,它们占用大量CPU资源,并且实际上使浏览器陷入瘫痪。这个网站是一个很好的例子: http://volar.makwan.net/index02.html

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

HTML中用于此效果的代码为< div id = fss class = fss全屏>< ; / div> -是否有一种方法可以在用户拖曳#home时禁用此DIV,以便在看不见背景时不会将资源专用于背景效果?

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?

推荐答案

您可以删除div的类(或id),当div离开视口(即屏幕)时,这会导致资源消耗。如果需要,您甚至可以在屏幕外添加一个临时班级。

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.

看看下面的代码片段。尽管看不到,但绿色框在屏幕上消失时会丢失类绿色,而会导致类橙色添加到它中(检查元素以查看其更改)。
然后,当它回到屏幕上时,div将获得类 green 并失去类 orange

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>

您可以申请< div id = fss class = fss full-screen>< / div> 的想法,当它不在屏幕上时禁用它

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

这篇关于如何关闭滚动上的JS / CSS背景效果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆