我有一个网站,使用php来填充来自MySql服务器的消息的一系列div。
我正在尝试编写每个消息的切换代码,以便它们可以轻松折叠。问题在于如何编写代码。观察:
<style type="text/css">
#slide {
}
#slide-body{
height: 100px;
overflow: hidden;
transition: height 10ms ease;
-moz-transition: height 10ms ease;
-ms-transition: height 10ms ease;
-o-transition: height 10ms ease;
-webkit-transition: height 10ms ease;
}
.collapsed {
height: 0px !important;
}
#less {
cursor: pointer;
text-align: left;
font-style: italic;
}
</style>
<script type="text/javascript">//<![CDATA[
window.onload=function(){
document.getElementById( 'slide' ).addEventListener( 'click', function() {
var body = document.getElementById( 'slide-body' );
if( body.className == 'collapsed' ) {
body.className = '';
document.getElementById( 'less' ).textContent = " [-]";
} else {
body.className = 'collapsed';
document.getElementById( 'less' ).textContent = " [+] The comment is now hidden. Press [+] to expand.";
};
} );
}//]]>
</script>
<div id="slide">
<div id="less">[-]</div>
<div id="slide-body">
Its a piece of cake to bake a pretty cake. Its a piece of cake to bake a pretty cake.
</div>
</div>
<div id="slide">
<div id="less">[-]</div>
<div id="slide-body">
Its a piece of cake to bake a pretty cake. Its a piece of cake to bake a pretty cake.
</div>
</div>
我非常感谢你能给我的任何建议。我尝试过按类而不是使用Id,但是没有任何事情发生。我是使用javascript的新手。
答案 0 :(得分:0)
我将html更改为使用类而不是ID:
<div class="slide">
<a href="#" class="less">[-]</a>
<div class="slide-body">
Its a piece of cake to bake a pretty cake. Its a piece of cake to bake a pretty cake.
</div>
</div>
<div class="slide">
<a href="#" class="less">[-]</a>
<div class="slide-body">
Its a piece of cake to bake a pretty cake. Its a piece of cake to bake a pretty cake.
</div>
</div>
并添加了这个jquery脚本:
$('.less').click(function(e){
var sbody = $(e.currentTarget).parent().find('.slide-body');
sbody.toggle();
$(this).text(sbody.is(':visible') ? '[-]' : '[+]')
})
HTH,
-Ted