您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息
免费发信息
三六零分类信息网 > 抚顺分类信息网,免费分类信息发布

javascript怎么实现弹出层

2025/1/25 19:07:52发布11次查看
javascript实现弹出层的方法:1、创建一个html示例文件;2、将待显示的内容先隐藏,在触发点击条件后,将原本隐藏的内容显示出来,代码如“document.getelementbyid(open).onclick = function(e){...}”;3、提供遮罩层将原先的页面内容全部遮住即可。
本教程操作环境:windows10系统、javascript1.8.5版本、dell g3电脑。
javascript怎么实现弹出层?
使用javascript实现弹出层效果
声明
阅读本文需要有一定的html、css和javascript基础
设计
实现弹出层效果的思路非常简单:将待显示的内容先隐藏,在触发某种条件后(如点击按钮),将原本隐藏的内容显示出来。
实现
<!doctype html><html><head> <title>window对象</title> <meta charset="utf-8"></head><body><a href="http://www.baidu.com">百度一下</a><button type="button" id="open">打开弹出层</button><div style="display: none;background: lightblue;border:1px solid green;" id="toast"> <!-- 设置display属性为none以隐藏内容 --> <p>这里是弹出层内容</p> <button type="button" id="close">关闭弹出层</button></div><script type="text/javascript"> var toast = document.getelementbyid("toast"); document.getelementbyid("open").onclick = function(e){ <!-- 定义点击事件显示隐藏内容 --> toast.style.display = "block"; toast.style.position = "fixed"; var winwidth = window.innerwidth; var winheight = window.innerheight; var targetwidth = toast.offsetwidth; var targetheight = toast.offsetheight; toast.style.top = (winheight - targetheight) / 2 + "px"; toast.style.left = (winwidth - targetwidth) / 2 + "px"; } document.getelementbyid("close").onclick = function(e){ <!-- 将显示的内容再次隐藏 --> toast.style.display = "none"; }</script></body></html>
显示效果如下:
但是我们可以注意到,在弹出隐藏内容之后我们还是可以通过链接进入百度页面。为了防止这种情况的发生,我们可以提供遮罩层将原先的页面内容全部遮住。代码如下:
<!doctype html><html><head> <title>window对象</title> <meta charset="utf-8"></head><body><a href="http://www.baidu.com">百度一下</a><button type="button" id="open">打开弹出层</button><div id="cover" style="display: none;position: fixed;width: 100%;height: 100%;top:0px;left:0px;background: gray;"> <!-- 通过遮罩层遮住背景 --> <div style="background: lightblue;border:1px solid green;" id="toast"> <!-- 设置display属性为none以隐藏内容 --> <p>这里是弹出层内容</p>   <button type="button" id="close">关闭弹出层</button></div></div><script type="text/javascript"> var toast = document.getelementbyid("toast"); var cover = document.getelementbyid("cover"); document.getelementbyid("open").onclick = function(e){ <!-- 定义点击事件显示隐藏内容 --> cover.style.display = "block"; toast.style.position = "fixed"; var winwidth = window.innerwidth; var winheight = window.innerheight; var targetwidth = toast.offsetwidth; var targetheight = toast.offsetheight; toast.style.top = (winheight - targetheight) / 2 + "px"; toast.style.left = (winwidth - targetwidth) / 2 + "px"; } document.getelementbyid("close").onclick = function(e){ <!-- 将显示的内容再次隐藏 --> cover.style.display = "none"; }</script></body></html>
这是再次测试下效果,如下图:
总结
上述内容只是简单实现了弹出层效果,但是通过添加更多的代码也可以在此基础上实现更复杂的功能。
推荐学习:《javascript视频教程》
以上就是javascript怎么实现弹出层的详细内容。
抚顺分类信息网,免费分类信息发布

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录