如何在崩溃和扩展时使用jQuery在加号和减号之间切换?

时间:2010-04-27 20:22:40

标签: jquery-ui jquery-plugins jquery

我正在使用以下代码。我想要做的是在展开或折叠视图上标记 + - 。我怎样才能做到这一点?这是代码:

<!--//---------------------------------+
//  Developed by Roshan Bhattarai  |
//  http://roshanbh.com.np         |
//  Fell Free to use this script   |
//---------------------------------+-->
<title>Collapsible Message Panels</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    //hide the all of the element with class msg_body
    $(".msg_body").show();
    //toggle the componenet with class msg_body
    $(".msg_head").click(function(){
        $(this).next(".msg_body").slideToggle(100);
    });
});
</script>
<style type="text/css">
body {
    margin: 10px auto;
    width: 570px;
    font: 75%/120% Verdana,Arial, Helvetica, sans-serif;
}
p {
    padding: 0 0 1em;
}
.msg_list {
    margin: 0px;
    padding: 0px;
    width: 383px;
}
.msg_head {
    padding: 5px 10px;
    cursor: pointer;
    position: relative;
    background-color:#FFCCCC;
    margin:1px;
}
.msg_body {
    padding: 5px 10px 15px;
    background-color:#F4F4F8;
}
</style>
</head>
<body>
<div align="center">
  <p>Click on the each news head to toggle
</p>

</div>
<div class="msg_list">
        <p class="msg_head">Header-1 </p>
        <div class="msg_body">
            orem ipsum dolor sit amet
        </div>

        <p class="msg_head">Header-2</p>
        <div class="msg_body">
            consectetuer adipiscing elit orem ipsum dolor sit amet
        </div>
</div>
</body>
</html>

3 个答案:

答案 0 :(得分:18)

msg_head的标记更改为类似的内容 -

<p class="msg_head">Header-1 <span>[-]</span></p>

并将切换功能更改为如下所示 -

$(".msg_head").click(function(){
    $(this).next(".msg_body").slideToggle(100);
})
.toggle( function() {
    $(this).children("span").text("[+]");
}, function() {
    $(this).children("span").text("[-]");
});

答案 1 :(得分:5)

最简单的方法是使用.toggleClass( className )。使用此方法,您可以在元素中添加或删除类。因此,将代码修改为下面的(未经测试的)代码应该可以解决问题。您需要将填充量偏移等量以适合您的图形文件。

<强>的JavaScript

$(".msg_head").click(function() {
    $(this).next(".msg_body").slideToggle(100);
    $(this).toggleClass('msg_head_expanded');
});

<强> CSS

.msg_head
{
  padding: 5px 10px;
  cursor: pointer;
  position: relative;
  background:#FFCCCC url('plus.png') no-repeat 0 50;
  margin:1px;
}

.msg_head_expanded
{
   background:#FFCCCC url('minus.png') no-repeat 0 50;
}

答案 2 :(得分:2)

我在自己的网站上有这个东西。我是这样做的:

$(".question").click(function () {
    if ($(this).next(".answer").is(":hidden")) {
        $(this).next(".answer").slideDown("slow");
        $(this).children('span').text('-');
    } else {
        $(this).next(".answer").slideUp("slow");
        $(this).children('span').text('+');
    }
}); 

HTML看起来像这样:

<div class="question">
    <span>+</span>blahblah
</div>
<div class="answer">blahblah</div>