【问题标题】:Transition with javascript, moving object使用 javascript 转换,移动对象
【发布时间】:2017-04-29 15:26:05
【问题描述】:

我正在尝试转换高度,但使用 JavaScript。 如我所见,它不起作用,所以我需要你的帮助。 这是代码,下面我将向您解释我的想法。

#button {
    display: inline-block;
    top = 0;
    left = 0;
}
<input type="button" id="button" onclick="myFunction()" value="Show">

<script>
    function myFunction(){
        var x = document.getElementById('button');
        var height = document.getElementById('myDIV').clientHeight;
        
        for(i = x.style.top; i <= height; i++){
            x.style.top = i + 'px';
        }
    }
</script>

所以这里的想法是:'height' 包含 DIV 的高度,我使用循环来增加 'top' 的值,以便在窗口中移动它,就像过渡一样。 'i' 是包含 'top' 的当前值的变量,当 i 小于高度时,它会增加并将当前值保存在顶部。

【问题讨论】:

  • css 应该是top:0;left:0;
  • 反正也不管用
  • 你在i&lt;=heightfor循环中也缺少;
  • 会不会是因为myDIV被隐藏了?以及我该如何解决?因为我想让 myDIV 保持隐藏状态
  • &lt;script&gt; 包含myFunction 应放在onclick="myFunction()" 之前

标签: javascript html css loops


【解决方案1】:

#myDivheight 设置为style 属性或css,将display 设置为block。使用window.getComputedStyle() 获取height 作为数字。

您可以使用Web Animations APIElement.animate() 函数将元素top0 设置为设置在元素.height 的值,同时将fill 设置为"forwards"

#button {
  display: inline-block;
  position: relative;
  top: 0;
  left: 0;
}

#myDIV {
  position: relative;
  display: block;
  height: 100px;
}
<script>
  var settings = ["0px"];

  function toggleAnimation(el, from, to) {
    el.animate([{
        top: from
      }, {
        top: to
      }], {
        duration: 2500,
        iterations: 1,
        fill: "forwards"
      })
      .onfinish = function() {
        settings.reverse(); // reverse `from`, `to` stored at `settings`
      }
  }

  function myFunction() {
    var x = document.getElementById("button");
    var height = window.getComputedStyle(document.getElementById("myDIV")).height;
    if (!settings[1]) settings[1] = height;
    toggleAnimation(x, settings[0], settings[1]);
  }
</script>

<span id="myDIV">
        <p>Pressure:</p>
        <p>Air gases:</p>
    </span>
<input type="button" id="button" onclick="myFunction()" value="Show">

【讨论】:

  • 很抱歉给您带来了困扰,但是当我点击它时,我应该做些什么改变让它回到顶部呢?
  • 我只需要颠倒这些值吗?
  • 是的,首先将top.animate() 设置为当前top,第二个top 设置为0
  • 好的,我会试试的,如果我做不到,我可以再给你写信吗?私信或其他?
  • 您可以自己通过替换属性中的值来实现。您还可以定义一个交换值的函数。
猜你喜欢
  • 2017-04-23
  • 2016-02-20
  • 1970-01-01
  • 2019-04-06
  • 1970-01-01
  • 2014-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多