<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<style type="text/css">
.box{ width:100px; height:100px; border:1px solid #ccc;}
</style>
<body>
<div class="box"></div>
<script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$(".box").click(function(){
$(this).toggle(function(){
$(this).css("background","red")
},function(){
$(this).css("background","blue")
});
})
})
</script>
</body>
</html>
自己试了一下,点击之后隐藏了....难道toggle()方法只能用来显示隐藏?
jquery 1.9.1这个版本已经删除toggle方法了,要用1.9以下的版本。
而且
不需要在外面绑定click事件了,直接这样就还了:
$(function(){
$(".box").toggle(function(){
$(this).css("background","red")
},function(){
$(this).css("background","blue")
});
});
用jquery.js版本可以
$(function(){
$(".box").toggle(function(){
$(this).css("background","red")
},function(){
$(this).css("background","blue")
});
});
jQuery 事件 - toggle() 方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<style type="text/css">
.box{ width:100px; height:100px; border:1px solid #ccc;}
</style>
<body>
<div class="box"></div>
<script src="http://libs.baidu.com/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$(".box").toggle(function(){
$(this).css("background","red")
},function(){
$(this).css("background","blue")
});
})
</script>
</body>
</html>
$('.box').toggle(function(){
$(this).css("background","red")
},function(){
$(this).css("background","blue")
});
是的toggle
只能用来隐藏
http://api.jquery.com/toggle/
Description: Display or hide the matched elements.
要不试试toggleClass
:
.box{ width:100px; height:100px; border:1px solid #ccc; background: blue}
.red { background: red;}
$(function(){
$(".box").click(function(){
$(this).toggleClass('red');
})
})