单击时展开div

时间:2014-11-26 07:44:26

标签: javascript jquery css onclick

我在这些论坛中搜索了一种方法来实现' jquery在点击时展开div

我找到了一个简单而理想的教程,但在重新编写代码时无法实现它。

此代码对当前的jquery仍然有效吗?我相信我已经完全复制了演示,只是不确定脚本的链接。

以下是我正在使用的教程[link:https://stackoverflow.com/a/20144029/1471333]

[DEMO][2]

$('.wrapper').find('a[href="#"]').on('click', function (e) {
    e.preventDefault();
    this.expand = !this.expand;
    $(this).text(this.expand?"Click to collapse":"Click to read more");
    $(this).closest('.wrapper').find('.small, .big').toggleClass('small big');
});

[link [2]: http://jsfiddle.net/mWcmg/1/]

这是我在[链接删除]的结果,其中演示资源文件有效,但我的编码无论出于什么原因都没有打开。也许我链接到的jquery已经改变了?

修改的  这是HTML代码的片段。

<div class="wrapper">
<div class="small">
<p>Lorem..</p>
</div>
<a href="#">Click...</a>
</div>

安迪

4 个答案:

答案 0 :(得分:1)

将您的javascript放入文档就绪事件中。因为在您的示例中,您在DOM准备好之前执行javascript。

$(document).ready(function()
{
    $('.wrapper').find('a[href="#"]').on('click', function (e) {
        e.preventDefault();
        this.expand = !this.expand;
        $(this).text(this.expand?"Click to collapse":"Click to read more");
        $(this).closest('.wrapper').find('.small, .big').toggleClass('small big');
    });
});

答案 1 :(得分:0)

试试这个:jsFiddle

HTML

<div class="wrapper">
<div class="small">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
<a id="click" href="#">Click...</a>
</div>

CSS

.small {
    height: 30px;
    overflow: hidden;
}
.big {
    height: auto;
}

的jQuery

$('#click').click(function() {
    $('div.wrapper').find('div').toggleClass('small big');
});

答案 2 :(得分:0)

您的代码是正确的,因此您可能忘记准备好文档(onDomready)。

您可以将代码放在$(document).ready(function(){...});

之间

像这样:

$(document).ready(function(){
    $('.wrapper').find('a[href="#"]').on('click', function (e) {
        e.preventDefault();
        this.expand = !this.expand;
        $(this).text(this.expand?"Click to collapse":"Click to read more");
        $(this).closest('.wrapper').find('.small, .big').toggleClass('small big');
    });
});

答案 3 :(得分:0)

只要您使用jQuery,您也可以利用它提供的功能。 toggle()方法允许您显示/隐藏组件,包含动画以及为您提供的所有内容。以下是我编写的组件的摘录,该组件将您指定的任何div转换为带有标题栏的可折叠窗格:

  CollapsiblePane.prototype.toggle = function( img ){
    var self = this, icon = ( ( self.selector.css( "display" ) === "none" ) ? "collapse" : "expand" );
  self.selector
     .toggle( 'blind', {}, 200, function(  ) {
        $( img ).attr( "src", self.path + "img/" + icon + ".png");
      });
  };

如果您想查看完整来源,可以在此处查看:https://github.com/robertdmunn/gadget-ui。除了你需要了解toggle()的内容之外,还有很多事情要做,但是如果你想了解用jQuery扩展你的UI组件可以做些什么,那么看看吧。

相关问题