伙计们,我正在制作一个菜单栏,但我一直在制作动画或移动它。这些是我的相关代码:
function navbar(){
document.getElementById("a").style.marginLeft = "50%";
.
.
.
function navbar2(){
document.getElementById("a").style.marginTop = "-100px";
}
$(document).ready(function(){
$("#a").click(function(){
navbar();
var x = $('#a');
$.when(x.css("margin-left")=="50%").done(function(){
navbar2();
});
});
});
我希望我的导航栏图标首先向左移动边距=50%;之后,当我的图标达到左边50%的空白时,将图标移动到顶部。但现在,当我点击图标时,它开始同时向上和向右移动。但我希望我的图标先向右,然后再向上。
有人能帮忙吗?
您可以使用jQuery这样做,而不需要navbar()
和navbar2()
:
$("#a").click(function() {
$(this).animate({
margin-left: "50%"
}, "slow")
.animate({
margin-top: "-100px"
}, "slow");
});
首先创建一个具有动画属性的CSS类。使用此属性,您可以告诉浏览器动画应该是什么、需要多长时间、是否有延迟以及更多选项。
现在是时候使用@keyframes
关键字创建动画了。在关键字之后指定动画的名称。在@keyframes
块中,可以继续执行动画的步骤。在下面的示例中,我使用了0%
、50%
和100%
作为动画的步骤或关键帧。这些数字表示起点(0%(、中点(50%(和终点(100%(。
在关键帧的块中,可以指定希望样式在该特定点处的样式。所以你可以说,一开始你不想要任何保证金,但在50%的时候,你希望保证金是左边的-50%
。然后在100%时,您希望左边的-50%
和上边的-100px
都是空白。
/**
* Define a class with an animation property.
* This specific class uses the navbar-animation animation which
* completes in 3 seconds without delay. It also has a linear easing
* and only runs once. The fill-mode specifies if the last keyframe
* of the animation should persist if the animation is finished.
* Otherwise your element would shoot back to its starting position.
*/
.animation {
animation-name: navbar-animation;
animation-duration: 3s;
animation-delay: 0s;
animation-timing-function: linear;
animation-iteration-count: 1
animation-fill-mode: forwards;
/* Or in shorthand */
animation: navbar-animation 3s 0s linear 1 forwards;
}
@keyframes navbar-animation {
0% {
/**
* This is the starting position of the animation.
* without any margins.
*/
margin: 0;
}
50% {
/**
* At the halfway point the element should be 50% to
* to the left.
*/
margin: 0 0 0 -50%;
}
100% {
/**
* At the end the animation has to be 50% to the left
* and 100px up.
*/
margin: 0 -100px 0 -50%;
}
}
因为您现在已经在CSS中指定了动画,所以您不必再在JavaScript中担心它,这使JS的复杂性大大降低。
现在所要做的就是添加上面指定的CSS类,并在单击应该触发动画的元素时添加它。
$(document).ready(function() {
// Select the element and store it in a variable so
// you don't have to select it again.
var $a = $('#a');
// Only add a CSS class to the element and let CSS
// handle the animation.
function addAnimation() {
$a.addClass('animation')
}
// Listen for click to call the addAnimation function.
$a.on('click', addAnimation);
});
这样可以创建所需的动画。我想补充一点,我鼓励您使用transform
属性而不是margin
来移动元素。transform
用于这种操作,而不会中断文档的流程并保持高性能。