Vanilla Javascript animate margin-section of section

时间:2017-09-24 22:15:58

标签: javascript html css web

我在让滑块工作时遇到问题。它是一个简单的点击按钮来进出各个部分的系统,但我遇到了让它运行的问题。 我在这里制作了一个codepen:https://codepen.io/ItsBrianAgar/pen/JrbZEz

这是我到目前为止的js。 它需要是Vanilla Js

    var nextSection = function() {
    var username = document.querySelector("input[name=\"username\"]").value;
    var password = document.querySelector("input[name=\"password\"]").value;
    if (username.length && password.length > 4) {
      return window.location = "appSection.html";
    } else {
      alert("username and password must be longer than 4 characters");
    }
  }

  var nextPage = function() {
    var elem = document.getElementsByClassName("app");
    var pos = 0;
    var posDiff = 0;
    var currentPos = elem[1].style.marginLeft;
    var id = setInterval(frame, 5);
    function frame() {
      if (posDiff == -320) {
        clearInterval(id);
        posDiff = 0;
      } else {
        pos--;
        for (var i = 0; i < elem.length; i++) {
          elem[i].style.marginLeft = pos + 'px';
        }
        posDiff = currentPos + pos;
      }
    }
  }

  document.getElementById("cancel").onclick = previousPage = function() {
    var elem = document.getElementsByClassName("app");
    var pos = 0;
    var id = setInterval(frame, 5);
    function frame() {
      for (var i = 0; i < elem.length; i++) {
        if (pos == 640) {
          clearInterval(id);
        } else {
          elem[i].style.marginLeft = pos + 'px';
          pos += 320;
        }
      }
    }
  }

1 个答案:

答案 0 :(得分:0)

您可以使用Element.animate()DOM元素设置动画

const [div, animationState, props] = [
  document.querySelector("div")
, ["click to animate", "click to reverse animation"]
, ["0px", "320px"] // from, to
];

div.textContent = animationState[0];

div.onclick = () => {
  div.animate({
      marginLeft: props
    }, {
      duration: 1000,
      easing: "linear",
      iterations: 1,
      fill: "both"
    })
    .onfinish = function() {     
      props.reverse();
      div.textContent = animationState.reverse()[0];         
    }
}
<div></div>