<script type="text/javascript">
var mh = 20;//最小高度
var step = 1;//每次变化的px量
var ms = 10;//每隔多久循环一次
function toggle(o){
if (!o.tid)o.tid = "_" + Math.random() * 100;
if (!window.toggler)window.toggler = {};
if (!window.toggler[o.tid]){
window.toggler[o.tid]={
obj:o,
maxHeight:o.offsetHeight,
minHeight:mh,
timer:null,
action:1
};
}
o.style.height = o.offsetHeight + "px";
if (window.toggler[o.tid].timer)clearTimeout(window.toggler[o.tid].timer);
window.toggler[o.tid].action *= -1;
window.toggler[o.tid].timer = setTimeout("anim('"+o.tid+"')",ms );
}
function anim(id){
var t = window.toggler[id];
var o = window.toggler[id].obj;
if (t.action < 0){
if (o.offsetHeight <= t.minHeight){
clearTimeout(t.timer);
return;
}
}
else{
if (o.offsetHeight >= t.maxHeight){
clearTimeout(t.timer);
return;
}
}
o.style.height = (parseInt(o.style.height, 10) + t.action * step) + "px";
window.toggler[id].timer = setTimeout("anim('"+id+"')",ms );
} window.onload = function(){
toggle(document.getElementById("ToggleObj"))
};
</script>
<style type="text/css">
div.xx{border:solid 1px;overflow:hidden;width:754px;}
div.xx span{border:solid 1px;border-width:0 0 1px;padding:0;margin:0;height:20px;line-height:20px;background:#f2f2f2;}
</style>
<div class="xx" id="ToggleObj"> <span onclick="toggle(this.parentNode)"> sfsf </span> <br>
12312313213123123131323
</div>
其实方法你已经写好了 ,只需要在页面加载的时候调一下就可以了window.onload = function(){
toggle(document.getElementById("ToggleObj")); //ToggleObj 要传一个对象进去
};
<div class="xx" id="ToggleObj"> <span onclick="toggle(this.parentNode)"> sfsf </span> <br>
12312313213123123131323
</div>
时候只有第一个起作用 其余的都不收缩
参考
function hidesubmenu(sid)
{eval("submenu" + sid + ".style.display=\"none\";");}
function showsubmenu(sid)
{
submenu1.style.display="none";
submenu2.style.display="none";
submenu3.style.display="none";
eval("submenu" + sid + ".style.display=\"block\";");
}
</script><div class="kuang">
<h1 id="img2"><a href="javascript:showsubmenu(1);">菜单一</a></h1>
<div id="submenu1" style="display:none;"><h2>菜单1</h2><h2>菜单1.1</h2><h2>菜单1.2</h2></div>
<h1 id="img3"><a href="javascript:showsubmenu(2);">菜单二</a></h1>
<div id="submenu2" style="display:none;"><h2>菜单2</h2><h2>菜单2.1</h2><h2>菜单2.2</h2></div>
<h1 id="img4"><a href="javascript:showsubmenu(3);">菜单三</a></h1>
<div id="submenu3" style="display:none;"><h2>菜单3</h2><h2>菜单3.1</h2><h2>3.2</h2></div>
</div>就是这么短的就可以做到伸缩效果,有人会说,那万一我要有多个呢?怎么办?
那上面的代码你只需给一小部分
submenu1.style.display="none";
submenu2.style.display="none";
submenu3.style.display="none";
只需把这部分改为循环的或者什么别的都可以