在Javascript中创建切换效果

时间:2016-04-06 22:14:45

标签: javascript html css

我刚开始学习动画的Javascript。我已经创建了这个超级简单的例子,当点击它时,从中心位置移动3个块,到顶部,左上角和右上角位置(我正在构建一种Context Action按钮类型的东西)。但我现在希望能够再次点击,如果动画是“out”,那么它将反向执行。我尝试添加if else,使用elem1.style.bottom == 350参数来定义pos是递增还是递减,但它不起作用。同样,我无法在点击之间保持clicked布尔值。

JSFiddle

HTML:

<body>

<p>
<button onclick="myMove()">Click Me</button>
</p> 

<div id ="container">
<div id ="animate1"></div>
<div id ="animate2"></div>
<div id ="animate3"></div>
</div>

</body>

的CSS:

#container {
  width: 400px;
  height: 400px;
  position: relative;
  background: yellow;
}
#animate1 {
  width: 50px;
  height: 50px;
  left: 175px;
  bottom: 175px;  
  position: absolute;
  background-color: red;
  z-index:3;
}
#animate2 {
  width: 50px;
  height: 50px;
  left: 175px;
  bottom: 175px;  
  position: absolute;
  background-color: blue;
}
#animate3 {
  width: 50px;
  height: 50px;
  left: 175px;
  bottom: 175px;
  position: absolute;
  background-color: green;
}

使用Javascript:

function myMove() {
  var elem1 = document.getElementById("animate1"); 
  var elem2 = document.getElementById("animate2"); 
  var elem3 = document.getElementById("animate3"); 
  var start = 350;
  var pos = 175;
  var id = setInterval(frame, 5);
  var clicked = false;
  function frame() {
    if (pos == 350) {
      clearInterval(id);
      clicked = !clicked;
    } else {
      if (clicked == false){ pos++; } else { pos--;}
      elem1.style.bottom = pos + 'px'; 
      elem1.style.left = start - pos + 'px'; 
      elem2.style.bottom = pos + 'px'; 
      elem2.style.left = pos + 'px'; 
      elem3.style.bottom = pos + 'px'; 
    } 
  }
}

我将如何实现这一目标?

2 个答案:

答案 0 :(得分:1)

我认为这就是你想要的:http://jsfiddle.net/3pvwaa19/20/

它会创建一个变量来跟踪动画是否已经发生并将pos变量移动到同一位置 - 在主函数之外 - 这样这些值就不会在以后丢失每次点击:

var moved = false;
var pos = 175;

答案 1 :(得分:0)

是的,您可以使用if(elem1.style.bottom ==&#34; 350px&#34;){...} else {...:

function myMove() {
  var elem1 = document.getElementById("animate1"); 
  var elem2 = document.getElementById("animate2"); 
  var elem3 = document.getElementById("animate3");
  if (elem1.style.bottom == "350px"){
    var start = 175;
    var pos = 350;
    var id = setInterval(frame, 5);
    function frame() {
      if (pos == 175) {
        clearInterval(id);
      } else {
        pos--; 
        elem1.style.bottom = pos + 'px'; 
        elem1.style.left = 2*start -  pos + 'px'; 
        elem2.style.bottom = pos + 'px'; 
        elem2.style.left =  pos + 'px'; 
        elem3.style.bottom = pos + 'px'; 
      }
    }
  } else {
    var start = 350;
    var pos = 175;
    var id = setInterval(frame, 5);
    function frame() {
      if (pos == 350) {
        clearInterval(id);
      } else {
        pos++; 
        elem1.style.bottom = pos + 'px'; 
        elem1.style.left = start - pos + 'px'; 
        elem2.style.bottom = pos + 'px'; 
        elem2.style.left = pos + 'px'; 
        elem3.style.bottom = pos + 'px'; 
      }
    }
  } 
}