jQuery切换显示/隐藏图像和文本

时间:2013-10-01 01:10:06

标签: jquery css toggle

我找到了这个jquery切换代码 here。现在我想添加一个垂直对齐到图像中间的文本“Click to Open”。

这是代码:

CSS:

.toggle{
    display:inline-block;
    height:48px;
    width:48px;
    background:url("http://icons.iconarchive.com/icons/pixelmixer/basic/48/plus-icon.png");
}
.toggle.expanded{
    background:url("http://cdn2.iconfinder.com/data/icons/onebit/PNG/onebit_32.png");
}

jQuery的:

$(document).ready(function(){
    var $content = $(".content").hide();
    $(".toggle").on("click", function(e){
        $(this).toggleClass("expanded");
        $content.slideToggle();
    });
});

HTML:

<div class="toggle"></div>
<div class="content">
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
</div>

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

喜欢这个吗?

添加:after个伪元素到切换,以及一些行高。

.toggle:after{
    content:"Click to Open";
    display:block;
    height:48px;
    line-height:48px;
    width:88px;
    margin-left:48px;
}
.toggle.expanded:after{
     content:"Click to Close";
}

<强> Demo

或者尝试这种方式:

HTML:

<div class="toggle">
  <span class="image"></span>
  <span class="text">Some Random text here. Hello</span>
</div>

的CSS:

.toggle {
    height:48px;
    line-height:48px;
}
.toggle .image {
    vertical-align:middle;
    display:inline-block;
    height:48px;
    width:48px;
    background:url("http://icons.iconarchive.com/icons/pixelmixer/basic/48/plus-icon.png");
}
.toggle .text {
    margin-left : 10px;
}

<强> Demo

答案 1 :(得分:0)

使div.toggle成为img而不是div。将src属性设置为CSS中指定的背景图像。给img下面的CSS

vertical-align:middle; 

为div.content提供内联显示。使用以下JS

var $content = $(".content").hide();
 $(".toggle").on("click", function(e) {
    $(this).attr("src", "http://cdn2.iconfinder.com/data/icons/onebit/PNG/onebit_32.png");
    $content.slideToggle();
 });

问题是你要垂直对齐的文字太长了,一旦它创建换行符,换行符下面的任何文字都不会沿着img的中心对齐。

请参阅new jsFiddle