首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >用js实现一个div弹出图层

用js实现一个div弹出图层

原创
作者头像
用户8703799
发布2023-04-10 11:39:04
发布2023-04-10 11:39:04
8.8K00
代码可运行
举报
文章被收录于专栏:javascript技术javascript技术
运行总次数:0
代码可运行

用js实现一个弹出图层,具体效果:

点击按钮后弹出图层,图层处于页面中间、带有阴影的圆角边框、图层中有input、提交按钮、关闭按钮、标题,弹出后背景页面不可点击、背景变灰。所有代码不分开、放在一个html中显示。

以下是一个简单的JavaScript代码示例:

代码语言:javascript
代码运行次数:0
运行
复制
<!DOCTYPE html>
<html>
<head>
 <title>弹出图层</title>
 <style>
  .overlay {
   position: fixed;
   top: 0;
   left: 0;
   width: 100%;
   height: 100%;
   background-color: rgba(0, 0, 0, 0.5);
   z-index: 9999;
   display: none;
  }
  .popup {
   position: absolute;
   top: 50%;
   left: 50%;
   transform: translate(-50%, -50%);
   background-color: #fff;
   padding: 20px;
   border-radius: 10px;
   box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
   text-align: center;
  }
  h2 {
   margin-top: 0;
  }
  input[type="text"] {
   padding: 10px;
   margin: 10px 0;
   border-radius: 5px;
   border: none;
   box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
   width: 100%;
   box-sizing: border-box;
  }
  button {
   padding: 10px 20px;
   background-color: #1c7cd6;
   color: #fff;
   border: none;
   border-radius: 5px;
   cursor: pointer;
  }
  button:hover {
   background-color: #15549a;
  }
  .close {
   position: absolute;
   top: 10px;
   right: 10px;
   width: 20px;
   height: 20px;
   border-radius: 50%;
   background-color: #ccc;
   color: #fff;
   font-size: 14px;
   text-align: center;
   line-height: 20px;
   cursor: pointer;
  }
  .close:hover {
   background-color: #999;
  }
 </style>
</head>
<body>
 <button id="open-popup">打开弹出图层</button>
 <div class="overlay" id="overlay">
  <div class="popup">
   <h2>弹出图层</h2>
   <input type="text" placeholder="请输入内容">
   <button>提交</button>
   <div class="close" id="close-popup">×</div>
  </div>
 </div>
 <script>
  var openPopupButton = document.getElementById("open-popup");
  var closePopupButton = document.getElementById("close-popup");
  var overlay = document.getElementById("overlay");
  openPopupButton.onclick = function() {
   overlay.style.display = "block";
   document.body.style.overflow = "hidden";
  }
  closePopupButton.onclick = function() {
   overlay.style.display = "none";
   document.body.style.overflow = "auto";
  }
 </script>
</body>
</html>

该代码使用了CSS样式,包含一个按钮和一个弹出图层。单击按钮将调用JavaScript函数来显示图层,并将背景页面设为不可点击状态。关闭按钮也是通过JavaScript函数来实现的,当用户单击关闭按钮时,它将隐藏弹出框并将背景页面状态还原。如果想隐藏JS功能逻辑,可用JShaman对JS代码进行混淆加密,加密后的代码是密文状态,不可读、不可分析。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档