---
title: "jQuery toggle() 没有显示，直接消失"
author: "michaelhqs"
date: "2013-12-02T17:06:59Z"
tags: ["jQuery"]
categories: ["Web前端"]
slug: "jquery-toggle"
draft: false
lastmod: "2013-12-02T17:06:59Z"
id: 1983866
url: "https://michaelhqs.iteye.com/blog/1983866"
---

今天在学习使用jQuery里面的动画功能，animate(),为了方便显示及显示效果测试，打算采用toggle函数，使动画能来回的移动。写了以下一段代码（纯为了学习的简陋代码）：

click me!

以上代码可以让页面中的div方块移动起来，但是加入toggle()之后，出现了对应div直接消失的问题: $("#pic1").toggle(function(){ $(this).animate({left: "500px"}, 1000); }, function(){ $(this).animate({left: "100px"}, 1000); }); 查阅文档后发现，toggle在1.9以后的版本中就只支持隐藏功能了，因此只能通过“多写多得到“（jQuery号称少写多的来着，去除toogle()的使用方法，让我肃然”不明觉挫“也哉！！）。 这里做了一个简单的判断，如果div的左边距大于500px则向左移，反之向右: $(function(){ $("#pic1").click(function(){ var $orgLeft = $("#pic1").css("left"); var $distance = 500; var $endLeft; if(parseInt($orgLeft) &gt; 500){ $endLeft = parseInt($orgLeft) - parseInt($distance); } else{ $endLeft = parseInt($orgLeft) + parseInt($distance); } $(this).animate({left: $endLeft}, 1000); }); }); 抛砖引玉，希望没砸到人: )