【问题标题】:change position on click-javascript animation更改 click-javascript 动画的位置
【发布时间】:2022-01-22 04:14:50
【问题描述】:

如何创建一个按钮以在第一次单击时通过 2 秒转换更改 div 的位置,并在第二次单击时将其恢复。

我这样做了,但它并没有把它带回来。

var d = document.getElementById("button");
d.addEventListener('click', function() {
  d.className = d.className + " move";
});

【问题讨论】:

标签: javascript html css


【解决方案1】:

更好的电话是d.classList.toggle("transitionClassName")

我从CSS transition between left -> right and top -> bottom positions复制了过渡

var d = document.getElementById("button");
d.addEventListener('click', function() {
  d.classList.toggle("move");
  d.classList.toggle("right");
});
.animate {
  height: 100px;
  width: 100px;
  background-color: #c00;
  transition: all 1s ease;
  position: absolute;
  cursor: pointer;
  font: 13px/100px sans-serif;
  color: white;
  text-align: center;
}


/* ↓ just to position things  */

.animate.left {
  left: 0;
  top: 50%;
  margin-top: -100px;
}

.animate.right {
  right: 0;
  top: 50%;
}

.animate.top {
  top: 0;
  left: 50%;
}

.animate.bottom {
  bottom: 0;
  left: 50%;
  margin-left: -100px;
}

.animate.left.move {
  left: 100%;
  transform: translate(-100%, 0);
}

.animate.right.move {
  right: 100%;
  transform: translate(100%, 0);
}

.animate.top.move {
  top: 100%;
  transform: translate(0, -100%);
}

.animate.bottom.move {
  bottom: 100%;
  transform: translate(0, 100%);
}
<button type="button" id="button" class="animate">Move</button>

【讨论】:

    【解决方案2】:

    const d = document.getElementById("button");
    
    d.style.transition = "0.8s";
    
    d.addEventListener('click', function(event) {
        event.target.classList.toggle("move");
    });
    .move {
      margin-left: 50px;
    }
    <button id="button">Click Me!</button>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-11
      相关资源
      最近更新 更多