Hola, necesito una animación que haga que un div vaya de izquierda a centro, pero no funciona. Este es mi código:
$(document).ready(function () { $(log).click(function () { var number = $(window).width() / 2; $(registrationDiv).animate({ left: number }, 200); $(registrationDiv).show(); $(loginDiv).hide(); }); });
este código coloca el div ligeramente a la derecha y no en el centro.
Hay al menos algunas formas de lograr esto (Javascript puro o jQuery, CSS estándar con transiciones o animaciones CSS, una biblioteca de animación o una combinación de algunos o todos estos) pero sugeriría usar jQuery/Javascript para capturar el evento de clic y agregar una clase con estilos de transición a su elemento de esta manera:
HTML
<div class="box"></div>
CSS
.box { height: 50px; width: 50px; background: black; position: fixed; // position the box relative to the viewport left: -25px; // hide the box by moving it over 50%. the other 50% is moved with translateX() top: 0; transform: translateX(-50%); // needed to align the center of the box with the center of the window } .box.animate { left: 50%; // position the box in the middle of the viewport transition: left 1000ms; // animate the 'left' CSS property with a duration of 1000 milliseconds }
jQuery
(function ($) { $(document).ready(function () { $(window).click(function () { const box = $(".box"); box.addClass('animate') }); }); })(jQuery);
Vanilla Javascript (alternativa al uso de jQuery)
window.addEventListener('DOMContentLoaded', () => { document.querySelector('.box').addEventListener('click', function(e) { e.target.classList.add('animate') }) });
La posición del div es relativa a la parte superior izquierda de un div (cuadro). Como tal, su punto de registrationDiv
Div (0,0) está exactamente en el centro de la pantalla.
Retire la mitad del ancho de su div de destino del number
$(document).ready(function () { $(log).click(function () { let halfChildWidth = $(registrationDiv).width() * .5 var number = $(window).width() / 2; $(registrationDiv).animate({ left: number - halfChildWidth}, 200); $(registrationDiv).show(); $(loginDiv).hide(); }); });