前端实践:如何实现一个弹窗

您所在的位置:网站首页 air2s弹窗怎么弄 前端实践:如何实现一个弹窗

前端实践:如何实现一个弹窗

2024-06-18 03:23| 来源: 网络整理| 查看: 265

前端实践:如何实现一个弹窗

​ 在前端开发中,我们经常会遇到需要设计弹窗的情形,今天就来看看如何用原生js写一个弹窗

功能说明

​ 我们要实现的功能是点击按钮弹出弹窗,然后点击右上角的关闭按钮或者点击其他非弹窗的区域弹窗消失。

HTML

​ 首先先写HTML布局:

点击打开弹窗 这是一个弹窗 ×

效果:

在这里插入图片描述

CSS * { padding: 0px; margin: 0px; } /* 弹窗背景 */ #modal { width: 100%; height: 100%; /* 默认隐藏 */ /* display: none; */ /* 固定定位 */ position: fixed; /* 设置在顶层 */ z-index: 1000; /* 设置位置 */ left: 0; top: 0; overflow: auto; background-color: rgba(0, 0, 0, 0.4); } /* 弹窗内容 */ #modal-content { position: relative; background-color: #fff; margin: 10% auto; border: 1px solid #888; width: 1000px; height: 580px; z-index: 1001; } /* 关闭按钮 */ #close { position: absolute; right: 20px; color: #aaa; float: right; font-size: 28px; font-weight: bold; } /* 设置关闭按钮的鼠标指针 */ #close:hover, #close:focus { color: black; text-decoration: none; cursor: pointer; }

效果: 在这里插入图片描述

然后我们要让弹窗先隐藏起来,使用display:none;或者visibility:hidden;

效果: 在这里插入图片描述

JavaScript

通过设置监听函数后来改变元素的样式display

// 点击按钮 var button = document.getElementById("button"); var modal = document.getElementById("modal") button.onclick = function () { modal.style.display = "block"; }; // 关闭按钮 document.getElementById("close").onclick = function () { modal.style.display = "none"; }; // 点击其他领域(即弹窗背景) window.onclick = function(event){ if(event.target ==modal){ modal.style.display = "none" } }

效果:

完善

最后我们根据需要,可以使弹窗的内容和图片无法被选中和复制

/* 设置页面不可选择,复制 */ -moz-user-select: none; -o-user-select: none; -khtml-user-select: none; -webkit-user-select: none; -ms-user-select: none; user-select: none;

设置图片无法被拖拽



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3