滚动后可见元素时开始动画

时间:2019-06-20 19:18:26

标签: javascript jquery animation scroll

我试图通过滚动查看面板时调用动画。

因此,当金面板进入视图时,如何稳定此动画触发器以使其仅动作-当动画不在视图中时重置/停止动画。或反转动画或受滚动方向控制-因此,如果您向下滚动,则框会向下移动-如果您向上滚动,则会重置为原始位置

$(function() {

  function myMove() {
    var elem = document.getElementById("myPerson");
    var pos = 0;
    var id = setInterval(frame, 10);

    function frame() {
      if (pos == 350) {
        clearInterval(id);
      } else {
        pos++;
        elem.style.top = pos + 'px';
        elem.style.left = pos + 'px';
      }
    }
  }


  var header = $("#vision");
  $(window).scroll(function() {
    var scroll = $(window).scrollTop();

    if (scroll >= 500) {
      header.removeClass('clearHeader').addClass("darkHeader");
      myMove()
    } else {
      header.removeClass("darkHeader").addClass('clearHeader');

    }
  });
});

enter image description here http://jsfiddle.net/v8g7m51j/2/

2 个答案:

答案 0 :(得分:0)

您可以使用getBoundingClientRect并检查该项目是否在页面视图中。

function isViewport (element) { 
   var rect = element.getBoundingClientRect ();
   return rect.bottom <0 || rect.right <0 || rect.left> window.innerWidth || rect.top>      
   window.innerHeight;
}

答案 1 :(得分:0)

我将代码放在这里

function myMove(type) {
  let element = document.getElementById('animate');
  element.removeAttribute('class');
  element.classList.add(type);
}

let count = false;
let position = document.documentElement.scrollTop;

window.addEventListener('scroll', e => {
  let scrolls = document.documentElement.scrollTop;
  let element = document.getElementById('animate');
  const mystage = document.querySelector('.myStage');

  if (!isViewport(mystage)) {
    if (scrolls > position) {
      myMove('down');
    } else {
      myMove('up');
    }
  } else {
    element.removeAttribute('class');
  }

  position = scrolls;
});


function isViewport(element) {
  let rect = element.getBoundingClientRect();
  return rect.bottom < 0 || rect.right < 0 || rect.left > window.innerWidth || rect.top > window.innerHeight;
}
#container {
  width: 400px;
  height: 400px;
  position: relative;
  background: yellow;
}

#animate {
  width: 50px;
  height: 50px;
  position: absolute;
  background-color: red;
}

.down {
  animation: down 1s ease-in-out forwards;
}

.up {
  animation: up 1s ease-in-out forwards;
}

@keyframes down {
  0% {
    transform: translate(0%, 0%)
  }

  100% {
    transform: translate(350px, 350px)
  }
}

@keyframes up {
  0% {
    transform: translate(350px, 350px)
  }

  100% {
    transform: translate(0%, 0%)
  }
}

.container {
  width: 100%;
  height: 1500px;
}

.red {
  background: red;
}

.blue {
  background: blue;
}
<div class="container red "></div>

<div id="container" class="myStage">
  <div id="animate"></div>
</div>

<div class="container blue"></div>