开发者社区 问答 正文

用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.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()方法只能用来显示隐藏?

展开
收起
小旋风柴进 2016-05-31 10:54:00 2650 分享 版权
1 条回答
写回答
取消 提交回答
  • 
    .box{ width:100px; height:100px; border:1px solid #ccc; background: blue}
    .red {  background: red;}
    $(function(){
            $(".box").click(function(){
                $(this).toggleClass('red');
            })
    2019-07-17 19:21:32
    赞同 展开评论
问答分类:
问答地址: