本文介绍如何使用JavaScript实现点击按钮显示指定层,并在点击页面其他区域时自动隐藏该层的功能。通过绑定点击事件和判断事件目标,实现简单的交互效果,适用于弹窗、菜单等场景。
JavaScript实现点击显示层与外点击隐藏功能
<!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"> <head> <meta http-equiv="Content-Type" content="text/html; charset=GB2312" /> <title>点击一个连接显示层~点击其他区域隐藏 练习 by 本站</title> <style type="text/css"> #myDiv{ border:1px solid #000000; width:200px; height:100px; background:#cccccc; } </style> </head> <body> <div id="myDiv" style="display:none;">本站</div> <input type="button" value="出来吧层" id="showDiv" /> </body> </html> [Ctrl+A 全选 注:引入外部Js需再刷新一下页面才能执行]