0

我创建了一个 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 或将其返回到原始的 200 像素。

知道我该怎么做吗?也许添加上下箭头图标之类的。

4

3 回答 3

4

以这种方式使用的toggle()函数在较新版本的 jQuery 中已被弃用和删除,请改用标志:

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

检查target等号是否this在单击内部其他元素时停止任何问题.strecher

于 2013-06-07T12:21:42.740 回答
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 本身时它不会这样做。

于 2013-06-07T12:20:16.270 回答
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);
        }
    );
    }
});
于 2013-06-07T12:35:55.987 回答