5

Как при втором нажатии на кнопку вернуть квадрат обратно? Код ниже.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script> 
$(document).ready(function(){

    $("button").click(function(){
        $("div").animate({left: '250px'});
    });
    
    
});
</script> 
</head>
<body>

<button>Start Animation</button>

<p>By default, all HTML elements have a static position, and cannot be moved. To manipulate the position, remember to first set the CSS position property of the element to relative, fixed, or absolute!</p>

<div style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>

</body>
</html>

2
  • $("div").animate({left: 0});
    – Qwertiy
    2 июл 2017 в 10:39
  • А как сделать, чтобы он останавливался? 2 июл 2017 в 10:42

2 ответа 2

2

используйте toggleclass и transition для плавности:

$("button").click(function(){
        $("div").toggleClass('move_right');
    });
div {
  left: 0px;
  transition: all .5s;
  background:#98bf21;
  height:100px;
  width:100px;
  position:absolute;
}
.move_right {
  left: 250px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button>Start Animation</button>

<p>By default, all HTML elements have a static position, and cannot be moved. To manipulate the position, remember to first set the CSS position property of the element to relative, fixed, or absolute!</p>

<div></div>

4
  • Чёт я записываю по ходу коряво всё)) 2 июл 2017 в 11:24
  • что коряво? добавил ваш html ещё - нажмите выполнить код, вроде то, что вы хотите...
    – Alex
    2 июл 2017 в 12:14
  • Да, теперь гуд) Просто я думал что это можно сделать с помощью animate ) 2 июл 2017 в 12:30
  • 1
    есть много способов решения задачи - я предложил один из них....
    – Alex
    2 июл 2017 в 12:45
0
    [https://codepen.io/mario-web/pen/JJzaKB][1]

    <div class="box"></div>
    <button>click my</button>

    .box{
      height: 100px;
      width: 100px;
      background: #000000;
      margin: 0px;
      position: relative;
      top: 0;
      left: 0;
    }

    $(function(){
      $('button').on('click', function(){
        var $box = $('.box');
          $box.animate({
            left: "150px"
          }, 1000)
          .animate({
            left: 0
          }, 1000)
      });
    });
1
  • Вот пожалуйста, по клику плавное перемещение блока, и возврат на место при помощи animate
    – Mario
    15 июл 2017 в 0:55

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.