javascript - 用toggle()方法如何实现背景色来回切换?

查看:106
本文介绍了javascript - 用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()方法只能用来显示隐藏?

解决方案

是的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');
        })
})

这篇关于javascript - 用toggle()方法如何实现背景色来回切换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆