Как анимировать размер ширины с левой стороны с помощью JS? - PullRequest
0 голосов
/ 01 марта 2019

Я пытаюсь научиться создавать что-то похожее на эту анимацию: https://dribbble.com/shots/5311359-Diprella-Login

Так что в настоящее время у меня возникает проблема, когда "зеленый" или "синий" в моем случае расширяется> движется> Сжимается, я не могу получить тот же эффект с использованием «Ширина», потому что он сжимается с правой стороны, где я хочу, чтобы он сжимался с левой стороны после его перемещения.

Присоединение моего CodePen: https://codepen.io/MariusZMM/pen/jJWebK

JS использовал:

var start = anime.timeline({
  easing: 'easeInOutSine',
  autoplay: false
});

start
  .add({
    targets: '.square',
    width: 600,
    duration: 500
  })
  .add(
    {
      targets: '.square',
      translateX: 400,
      duration: 500
    },
    '-=100'
  )
  .add({
    targets: '.square',
    width: 400,
    duration: 500
  });

document.querySelector('.btn').onclick = function() {
  start.play();
  if (start.began) {
    start.reverse();
  }
};

Я также пытался использовать Padding, но я думаю, что AnimeJS не нравятся значения 0 0 0 300px

Ответы [ 2 ]

0 голосов
/ 01 марта 2019

Вот версия анимации только для CSS.

Я использую визуально скрытый флажок, кнопка - label, которая управляет флажком, и анимации CSS переключаются в состоянии проверки.

Единственное, что он выполняет начальную анимацию в обратном порядке при загрузке.

Редактировать: Я на самом деле исправил это с небольшим изменением CSS (:not(indeterminate))и дополнительный фрагмент JS при загрузке, который устанавливает флажок indeterminate.

const checkbox = document.getElementById('sign-in-state');
checkbox.indeterminate = true;
@keyframes login {
	0% {
		left: 0;
		width: 40%;
	}
	50% {
		width: 60%;
	}
	100% {
		left: 60%;
		width: 40%;
	}
}
@keyframes logout {
	0% {
		left: 60%;
		width: 40%;
	}
	50% {
		width: 60%;
	}
	100% {
		left: 0%;
		width: 40%;
	}
}

.sign-in-checkbox:not(:indeterminate):not(:checked) + .box .square {
  --animation-name: login;
}

.sign-in-checkbox:not(:indeterminate):checked + .box .square {
	--animation-name: logout forwards;
}

.window {
  position: absolute;
  width: 100%;
  height: 100%;
  background: #c73030;
  z-index: 9999;
}
.box {
  position: absolute;
  top: 50%;
  left: 50%;
		overflow: hidden;
  transform: translate(-50%, -50%);
  width: 100vw;
  height: 100vh;
  background-color: #f7986c;
  z-index: -999;
}

.square {
		animation: var(--animation-name) 600ms reverse ease-in-out;
  position: absolute;
		right: auto;
  top: 0;
  width: 40%;
  height: 100%;
  background-color: cornflowerblue;
}


.btn {
	display: flex;
	align-items: center;
	justify-content: center;
	color: white;
	font-family: sans-serif;
  position: absolute;
  width: 200px;
  height: 70px;
  top: 80%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #444;
}

.visually-hidden { /* https://snook.ca/archives/html_and_css/hiding-content-for-accessibility */
    position: absolute !important;
    height: 1px; width: 1px;
    overflow: hidden;
    clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
    clip: rect(1px, 1px, 1px, 1px);
}
<input type="checkbox" id="sign-in-state" class="visually-hidden sign-in-checkbox">		
<div class="box">

			<div class="square">
				<label class="btn" for="sign-in-state">
					
					<div class="sI">Sign In</div>
				</label>
			</div>

		</div>
0 голосов
/ 01 марта 2019

Проверьте это:

<!DOCTYPE html>
<html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <style>
        .window {
            position: absolute;
            width: 100%;
            height: 100%;
            background: #c73030;
            z-index: 9999;
        }

        #box {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 1000px;
            height: 500px;
            background-color: #f7986c;
            z-index: -999;
        }

        #square {
            position: absolute;
            top: 0;
            width: 400px;
            height: 100%;
            background-color: cornflowerblue;
        }

        #btn {
            position: absolute;
            width: 300px;
            height: 70px;
            top: 80%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: #444;
        }
    </style>

</head>

<body>
    <div id="box">

        <div id="square">
            <button id="btn">
                <div id="sI">Sign In</div>
            </button>
        </div>

    </div>


    <script>
        var animated = false;

        function animate() {
            $('#square').animate({
                width: '600',
                right: '0'
            }, 300, 'swing');
            $('#square').animate({
                width: '400'
            }, 300, 'swing');
            $('#square').css("left", "");
            animated = true;
        }

        function reverseAnimate() {
            $('#square').animate({
                width: '600',
                left: '0'
            }, 300, 'swing');
            $('#square').animate({
                width: '400'
            }, 300, 'swing');
            $('#square').css("right", "");
            animated = false;
        }

        $('#btn').click(function() {
            if (!animated) { //If it has not been animated, animate!
                animate();
            } else {
                reverseAnimate();
            }
        });
    </script>
</body>

</html>

Я использовал jQuery и изменил несколько вещей, чтобы они немного больше походили на пример.Кроме того, мне понравилось ваше использование .reverse (), но я не использовал его в моем случае.

...