首页 > 解决方案 > 不在视口中时移除元素

问题描述

当元素位于视口中时,我想在元素上触发动画(而不仅仅是转换)。我读到如果您可以在视口中创建元素并在它不在视口中时将其删除,您可以这样做。

当元素不在视口中时,我遇到了删除元素的挑战。

此代码用于在元素位于视口中时向元素添加和删除类

var scroll = window.requestAnimationFrame ||
             // IE Fallback
             function(callback){ window.setTimeout(callback, 1000/60)};

//create array of all elements with specific class
var elementsToShow = document.querySelectorAll('.show-on-scroll');

//create  loop function cycles above array calls function on it, adds clss if functions returns true, loop runs loop
function loop() {

    Array.prototype.forEach.call(elementsToShow, function(element){
      if (isElementInViewport(element)) {
        element.classList.add("is-visible");
} else {
element.classList.remove("is-visible");

}
});
scroll(loop);
}

// Call the loop for the first time
loop();

// Helper function from: http://stackoverflow.com/a/7557433/274826
//the function that will return true checks for list element in viewport
function isElementInViewport(el) {
// special bonus for those using jQuery
  if (typeof jQuery === "function" && el instanceof jQuery) {
    el = el[0];
  }
  var rect = el.getBoundingClientRect();
  return (
    (rect.top <= 0
      && rect.bottom >= 0)
    ||
    (rect.bottom >= (window.innerHeight || document.documentElement.clientHeight) &&
      rect.top <= (window.innerHeight || document.documentElement.clientHeight))
    ||
    (rect.top >= 0 &&
      rect.bottom <= (window.innerHeight || document.documentElement.clientHeight))
  );
}

在 Array.prototype.forEach.call 中,我添加了这段代码,我一直在探索(以及许多其他变体)。现在与有更多 js 经验的人核实更有意义。

有没有人对这种结构足够熟悉,可以快速通过?


Array.prototype.forEach.call(elementsToShow, function(element){
      if (isElementInViewport(element)) {
        element.classList.add("is-visible");

if (element.matches('this-element') && element.lastChild.matches("is-animated")){
const tag = document.createElement("p");
tag.id = "is-animated";
var textTag = document.createTextNode("Some text in the tag.");
tag.appendChild(textTag);
document.getElementById("this-element").appendChild(tag);
}

} else {
element.classList.remove("is-visible");

if(element.matches('is-animated')){
element.remove();
}

}
});
scroll(loop);
}

在 html 中有带有 id 的 div 和带有几个孩子的类“this-element”

标签。

标签: javascriptcss-animationsviewportrequestanimationframeremovechild

解决方案


这是一个红鲱鱼。解决方案不是在看不见的情况下移除元素,而是更改动画和过渡持续时间,以便它们快速结束。看这里:

function loop() {

Array.prototype.forEach.call(elementsToShow, function(element){

if (isElementInViewport(element)) {
element.classList.remove("end-transitions");
element.classList.add("is-visible");
}

else {
element.classList.remove("is-visible");
element.classList.add("end-transitions");
}
});

scroll(loop);
}


其中.end-transitions包含:

.end-transitions{
animation-duration:0s !important;
animation-delay:0s !important;
transition-duration: 0s !important;
transition-delay:0s !important;
}

推荐阅读