[英]Don't know how to use .toggle()
我有一个徽标,在菜单上单击时,字母T和H以及字母animatie彼此相距约400px。 当他们设置了动画后,导航将显示:轻松,但是当我再次单击汉堡菜单时,我希望导航以相同的动画关闭。 我尝试了不同的.toggle()函数,但是我不知道如何使其工作。 这就是现在的样子,我只是想不出如何切换菜单。
有没有人知道该怎么做,或者有任何建议吗? 非常感激!
(这是动画和淡入导航的工作代码)
$( "#myMenu" ).click(function() {
$( ".letterT" ).animate({
marginLeft: "-200px",
borderWidth: "10px"
}, 1000 );
});
$( "#myMenu" ).click(function() {
$( ".letterH" ).animate({
marginLeft: "400px",
position: "absolute",
borderWidth: "10px"
}, 1000 );
});
$( "#myMenu" ).click(function() {
$( "nav" ).fadeIn( 2000)
});
上面的代码只能运行一次。 一键单击,现在我尝试使用.toggle(),但是当我这样做时,它立即用动画隐藏了我的菜单。.而且我找不到菜单按钮了。
(这是我尝试用于切换的无效代码)
$(function(){
$('#myMenu').toggle(function(){
$( ".letterT" ).animate({
marginLeft: "-200px",
}, 1000 );
$( ".letterH" ).animate({
marginLeft: "400px",
position: "absolute",
}, 1000 );
//the code above should start the animation,
//and below it should animate back when I click on the menu
}, function(){
$( ".letterT" ).animate({
marginLeft: "200px",
}, 1000 );
$( ".letterH" ).animate({
marginLeft: "-400px",
position: "absolute",
}, 1000 );
});
});
注意:您加载了jQuery库的三倍。 您只需要一次。
您尝试做的是使用“老方法” toggle()
。 您可以阅读API说明 :
此方法签名在jQuery 1.8中已弃用,在jQuery 1.9中已删除。 jQuery还提供了一个名为.toggle()的动画方法,用于切换元素的可见性。
因为您使用的jQuery版本高于1.8,所以toggle()
函数仅显示/隐藏一个元素。
您有几种选择:您可以使用plugin ,但是我喜欢Dom的解决方案 ,该解决方案使用变量来跟踪状态。
您的JavaScript代码将变为:
var oddClick = true; // <-- The variable to keep track of the state
$("#myMenu").click(function () {
if (oddClick) {h
$(".letterT").animate({
marginLeft: "-200px",
borderWidth: "10px"
}, 1000);
$(".letterH").animate({
marginLeft: "400px",
position: "absolute",
borderWidth: "10px"
}, 1000);
$("nav").fadeIn(2000);
}
else { // We put it back as it was before.
$(".letterT").animate({
marginLeft: "0",
}, 1000 );
$(".letterH").animate({
marginLeft: "-0.3em",
position: "absolute",
}, 1000 );
$("nav").fadeOut(500);
}
oddClick = !oddClick; // We toggle the variable everytime the button is clicked.
});
我创建了一个jsFiddle来向您展示: http : //jsfiddle.net/grd7z1g8/1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.