单击时展开div

时间:2013-06-07 12:16:05

标签: javascript jquery html css

我创建了一个div,其内容的完整高度设置为500px。 500px的前200px就是预览。所以我把它的高度设置为200px和overflow: hidden。然后我添加了这个脚本:

<div class="stretcher">
<script type="text/javascript">  
    $('.stretcher').toggle(
        function(){
            $(this).animate({'height': '500px'}, 300);
        }, 
        function(){
            $(this).animate({'height': '200px'}, 300);
        }
    );
</script>

这有效,但问题是我需要div的内容可点击。但是,使用此脚本无论我单击它还是展开div或将其返回到原始的200px。

知道我该怎么做吗?也许上下添加箭头图标或其他东西。

3 个答案:

答案 0 :(得分:4)

在较新版本的jQuery中不推荐使用以这种方式使用的toggle()函数,而是使用标志:

$('.stretcher').on('click', function(e) {
    if (e.target === this) {
        var h = $(this).height() > 220;
        $(this).animate({'height': ( h ? 200 : 500 ) }, 300);
    }
});

在点击target

中的其他元素时,检查this等于.strecher是否停止了任何问题

答案 1 :(得分:2)

试试这个......

<div class="stretcher">
    <div class="clickable"></div>
</div>
<script type="text/javascript">  
    $('.clickable').toggle(
        function()
        {
            $(this).parent().animate({'height': '500px'}, 300);
        }, 
        function()
        {
            $(this).parent().animate({'height': '200px'}, 300);
        }
    );
</script>

您有一个名为clickable的区域,当您点击该区域时,它会为父容器div设置动画,但是当您单击div本身时它将不会这样做。

答案 2 :(得分:0)

您可以将代码包装在具有完全匹配的函数中。正如@adeneo指出的那样。下面以一种方式使用您现有的代码。

$('.stretcher').on('click', function(e) {
    if (e.target === this) {
        $('.stretcher').toggle(
        function(){
            $(this).animate({'height': '500px'}, 300);
        }, 
        function(){
            $(this).animate({'height': '200px'}, 300);
        }
    );
    }
});
相关问题