我在让我的 slider 工作时遇到问题。这是一个简单的系统,只需点击按钮即可进出各个部分,但我在使用它时遇到了问题。 我在这里做了一个代码笔: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;
}
}
}
}
最佳答案
您可以使用 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>
关于javascript - Vanilla Javascript 动画部分的左边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46395387/