简体   繁体   中英

How to move(animate) a button to a certain position on click and return to original position if click elsewhere?

假设我们有一个按钮<button id="btn">I'm a button</button>它的位置在中央。现在,当我单击此按钮时,它应该移动到左上角。在其他位置单击时在屏幕上,将按钮返回到原始位置(中心),以便下次我单击该按钮时,它应该重复过渡。

您可以使用jQuery.animate()实现此目的。

Maybe this is the easiest solution for you. Pure css without any javascripts.

 #btn { position: fixed; right: 50%; top: 50%; margin-right: -84px; transition: all 0.3s linear; } #btn:focus { top:0; right: 100%; } 
 <button id="btn">I'm a button</button> 

You can also use jquery, binding "focus" and "blur" event on the button, and animate it to the #btn:focus style values.

I tried to make it with javascript maybe like this you mean https://jsfiddle.net/90c23wbr/

<div class="text-center">
  <button id="button" class='btn btn-primary to-center'>button</button>
</div>

css :

.btn {
  position:absolute;
  transition: 1s ease;
}
.to-center {
  top:50%;
}
.to-top {
  top:5%;
}

and js:

var removeClass = true;

$("#button").click(function () {
   $(".btn").addClass('to-top');
   removeClass = false;
});

$("#button").click(function() {
  removeClass = false;
});

$("html").click(function () {
   if (removeClass) {
     $(".btn").removeClass('to-top');
   }
   removeClass = true;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM