本文介绍一种常见的网站交互效果,通过JavaScript实现点击总分类复选框自动选中所有子分类,以及当所有子分类被选中时自动选中总分类的逻辑。该脚本常见于分类导航场景,提升用户操作便捷性。
复选框联动效果描述
在许多网站中,这是一种非常常见的交互效果:当用户点击总分类的复选框时,系统会自动选中该总分类下的所有子分类复选框;反之,如果用户手动选中了某个总分类下的所有子分类复选框,系统也会自动将总分类的复选框标记为选中状态。
脚本来源与实现背景
这一实现灵感来源于MSN网站,笔者在浏览时注意到该效果,并尝试自行编写了相应的脚本代码。
代码示例与运行说明
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title></title> <script type="text/javascript"> function checkAll(str){ var a=document.getElementById("t"+str).getElementsByTagName("input"); var b=document.getElementById("d"+str); for(var i=0;i </head> <body> <center> <div style="width:90%;text-align:left;border:1px solid #ccc;height:25px;line-height:25px"><input type="checkbox" id="d1" onclick="checkAll('1')"/>休闲娱乐</div> <div style="width:90%;text-align:left;border:1px solid #ccc;" id="t1"> <input type="checkbox" onclick="fixChk('1')" />书籍及杂志 <input type="checkbox" onclick="fixChk('1')" />音乐及影碟 <input type="checkbox" onclick="fixChk('1')" />旅游 </div> </center> </body> </html> [Ctrl+A 全选 注:引入外部Js需再刷新一下页面才能执行]