窗口中div居中的动画



嗨,我需要一个动画,使div从左边到中间,但它不工作。这是我的代码:

$(document).ready(function () {
$(log).click(function () {
var number = $(window).width() / 2;
$(registrationDiv).animate({ left: number }, 200);
$(registrationDiv).show();
$(loginDiv).hide();
});
});

这段代码将div稍微放到右边,而不是中间。

div的位置相对于div (box)的左上角。这样你的registrationDiv(0,0)点正好在屏幕的中央。

number中删除目标div的一半宽度

$(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();
});
});

至少有几种方法可以实现这一点(纯Javascript或jQuery,香草CSS与过渡或CSS动画,动画库,或一些或所有这些的组合),但我建议使用jQuery/Javascript捕捉点击事件,并添加一个类与过渡样式到你的元素,像这样:

<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);

普通Javascript(替代jQuery)

window.addEventListener('DOMContentLoaded', () => {
document.querySelector('.box').addEventListener('click', function(e) {
e.target.classList.add('animate')
})
});

CodePen演示

最新更新