【问题标题】:Best Practice for Expanding Divs扩展 div 的最佳实践
【发布时间】:2026-02-09 11:35:02
【问题描述】:

我目前正在研究一种根据内容动态扩展 div 的解决方案。我几乎已经整理好了一个解决方案,但想知道是否有人可以检查代码以确保其高效并符合最佳实践?

有问题的page

代码是:

<script>
$(document).ready(function()
  {
   $(".row").each(function() { 
           $(this).height($(this).find('.topHeight').height()); 
            //Only shrink div if the user has javascript on.
    });

   $(".btns").click(function(){ //On click of the expand button    

        var el = $(this).closest('div[class^="row"]');//The Div Element to be animated.
        var curHeight = el.height(); //The current height.
        var fullHeight = el.height('auto').height(); //Temporarily sets the height to auto and returns it to the variable "fullHeight".
        el.height(curHeight); //Resets the height to the previous height.
        var minHeight = $(this).closest('div[class^="topHeight"]').height() + 10;//Gets the minimum height setting from CSS.

        if (el.height() != fullHeight) { //If the div is not at full height

            el.stop().animate({height: fullHeight}, 500);
             //Animate to full size.
           el.find('#open').html('Click to Read less');

        } else if (el.height() != minHeight) { //else if it is not at minimum height

            el.stop().animate({height: minHeight}, 1500, 'easeInOutQuart');
             //then shrink to minimum height.
             el.find('#open').html('Click to Read More');

        }
    });
});
</script>

对我来说它看起来有点效率低下,但到目前为止,这是我让它正常工作的唯一方法!

所以真的只是寻找一些指针,

谢谢, 亚当

【问题讨论】:

标签: jquery performance html


【解决方案1】:

该功能似乎有点复杂?

如果我理解正确的话,我会这样做:

$('.row').find('button').click(function(){
    $(this).closest('.shadow').find('.extra').slideToggle();
});  

剩下的就是 CSS。

工作JSFiddle

【讨论】:

  • 哇,我真的不知道你能做到这一点......谢谢!