jQuery+CSS 半开折叠效果原理及代码(自写)

  一个项目想用jQuery做一个可以半折叠的DIV元素,苦于jQueryUI中accordion没有提供相关的方法,就自己写了个。以前使用jQueryUI的时候发现能够用的accordion全部折叠起来了,没办法设置折叠的最小高度。

  代码质量很低,希望老鸟能够指点指点。

  下图是效果展示,能够借由jQuery的函数展开收缩

jQuery+CSS 半开折叠效果原理及代码(自写)

  

复制代码 代码如下:

  //author: hlhr

  //require: Jquery1.4 and above

  function animate_toggle_height(maxh,minh,maxo,mino,element,speed) {//这个是纵向的,参数解释:最大高度,最小高度,最大透明度,最小透明度,元素,动画速度

  if (element.css("height")==minh.toString().concat("px")){//如果是最小高度就展开

  element.animate({

  height:maxh,

  opacity:maxo

  },{queue: false},speed);

  return "Fold"

  }

  if (element.css("height")==maxh.toString().concat("px")){//如果是最大高度就折叠

  $(this).html("");

  element.animate({

  height:minh,

  opacity:mino

  },{queue: false},speed);

  return "Read more";

  }

  }

  function animate_toggle_width(maxw,minw,maxo,mino,element,speed) {

  if (element.css("width")==minw.toString().concat("px")){

  element.animate({

  width:maxw,

  opacity:maxo

  },{queue: false},speed);

  return "Fold"

  }

  if (element.css("width")==maxw.toString().concat("px")){

  element.animate({

  width:minw,

  opacity:mino

  },{queue: false},speed);

  return "Read more";

  }

  }

  

复制代码 代码如下:

  <html>

  <head>

  <script src="jquery-1.9.1.min.js"></script><!--需要jquery库-->

  <script src="jqslider.js"></script><!--链接上文的js库-->

  <style>

  body{margin: 0 auto; text-align:center;}

  .slide{font-size:20px; overflow: hidden; width: 500px; }

  #content{margin:0 auto; width: 500px;}

  .viewbutton{position:relative; text-align: right;}

  </style>

  </head>

  <body>

  <fieldset id="content">

  <div class="slide">

  <a class="viewbutton" href="#">

  Read more

  </a>

  <p>slide!</p>

  <p>slide!</p>

  <p>slide!</p>

  <p>slide!</p>

  <p>slide!</p>

  </div>

  </fieldset>

  <p />

  <fieldset id="content">

  <div class="slide">

  <a class="viewbutton" href="#">

  Read more

  </a>

  <p>slide!</p>

  <p>slide!</p>

  <p>slide!</p>

  <p>slide!</p>

  <p>slide!</p>

  </div>

  </fieldset>

  <script type="text/javascript">

  var max_h=300;

  var min_h=100;

  //var max_w=500;

  //var min_w=10;

  var max_o=1;

  var min_o=0.3;

  $(".slide").css({opacity:min_o});//设置初始的透明度

  $(".slide").css({height:min_h});//设置初始的高度

  $(".viewbutton").click(function(){//这里只是调用了纵向展开,也可以调用横向展开

  $(this).html(animate_toggle_height(max_h,min_h,max_o,min_o,$(this).parent(),500));//自动识别为viewbutton的上一级进行动画

  });

  </script>

  </body>

  </html>

  viewbutton的层级可自行修改,但要注意动画的目标是什么。我写的viewbutton会对它上一级的那个div做动画,所以就不用把选择器写得过于复杂了。