文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

原生JavaScript实现模态框的示例代码

2024-04-02 19:55

关注

原生js封装模态框

最近需要一个模态框,然后一种是提示类的,一种是确认类型,我就想着再网上找一个然后修改一下,结果找到了,但是不深特别合适,我再次基础上在做了修改,对功能有所增强,纯原生写的,没有任何依赖性,适应性比较强,值copy即可使用。

配置:可以在实例化时对options进行参数设置,达到自己想要的效果

示例效果

代码

HTML部分

<head>
		<meta charset="utf-8">
	 
		<title>弹出框</title>
	</head>

CSS部分

.mask {
			position: fixed;
			top: 0;
			bottom: 0;
			left: 0;
			right: 0;
			
			background: #bfbfbf;
			opacity: 0.5;
		}

		.modal {
			position: fixed;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			width: 400px;
			background-color: aliceblue;
			border-radius: 5px;
			z-index: 99;
			border: 1px solid rgba(0, 0, 0, 0.2);
		}

		.modal .modalTitle {
			height: 50px;
			box-sizing: content-box;
			display: flex;
			align-items: center;
			justify-content: space-between;
			border-bottom: 2px solid #eeeeee;
			padding: 0 16px;
		}

		.modalTitle .closeModal {
			width: 20px;
			height: 20px;
			border-radius: 5px;
			line-height: 20px;
			text-align: center;
			font-size: 14px;
			cursor: pointer;
			background-image: url('https://typroas.oss-cn-hangzhou.aliyuncs.com/typroaImg/close.png');
			background-size: 100% 100%;

		}


		.modalTitleText {
			margin: 0 auto;
			font-size: 17px;
		}



		.modal .main {
			box-sizing: border-box;
			padding: 16px;
			height: calc(100% - 80px);
		}

		.modal .footer {
			height: 50px;
			text-align: right;
			box-sizing: border-box;
			padding-right: 16px;
			display: flex;
			align-items: center;
			justify-content: flex-end;
		}

		.footer .btnLeft,
		.footer .btnRight {
			width: 120px;
			height: 35px;
			text-align: center;
			line-height: 30px;
			border: none;
			border-radius: 0.2rem;
			margin-left: 8px;
			background-color: #dddddd;
		}

		.footer .btnOk {
			width: 120px;
			height: 35px;
			text-align: center;
			line-height: 30px;
			border: none;
			border-radius: 0.3rem;
			background-color: #1d73d3;
			margin: 0 auto;
			font-size: 17px;
			color: white;
		}

		.footer .btnLeft:hover,
		.footer .btnRight:hover {
			background-color: #1D73D3;
			color: #FFFFFF;
		}

JS部分


			function Modal(options) {
				options = Object.assign({
					lateRelease: options.lateRelease ? options.lateRelease : false, //是否开启延时关闭
					lateReleaseTime: options.lateReleaseTime ? options.lateReleaseTime : 5000, // 延时关闭时间
					isCreateOpen: options.isCreateOpen ? options.isCreateOpen : true, //是否创建完毕后就打开弹出框
					type: options.type ? options.type : 'hint', // hint:提示框 confirm:确认框
					isTopRightcancel: true, // 是否需要右上角小x取消按钮
					modalTitle: options.modalTitle ? options.modalTitle : '温馨提示',
					backgroundColor: options.backgroundColor ? options.backgroundColor : '#fff', // 背景颜色
					mask: options.mask ? options.mask : true, //是否显示遮罩层,
					content: options.content ? options.content : '', //弹框内容
					cancelText: options.cancelText ? options.cancelText : '取消', //取消按钮文字
					okText: options.okText ? options.okText : '确认', // 确认按钮文字,
					width: options.width ? options.width : 500, //对话框的宽度
					onCancel: options.onCancel ? options.onCancel : this.closeModal, //取消按钮回调,默认是关闭弹框
					cancelCallBack: options.cancelCallBack ? options.cancelCallBack : () => {
						console.log('你点击了取消');
					}, //取消回调
					onOkCallBack: options.onOkCallBack ? options.onOkCallBack : () => {
						console.log('你点击了确认');
					}, // 确认按钮回调
				}, options);
				this.options = options;
				// 创建遮罩层
				function createMask() {
					let mask = document.createElement('div')
					mask.className = 'mask';
					document.body.appendChild(mask);
				}
			
				// 创建modal弹框
				function createModal(type) {
			
					let modal = document.createElement('div');
					let modalTitleDom = document.createElement('div');
					let main = document.createElement('div');
					let footer = document.createElement('div');
					let btnLeft;
					let btnRight;
					let btnOk;
					let closeIcon;
					if (type == 'hint') {
						btnOk = document.createElement('button');
						btnOk.className = 'btnOk';
					} else if (type == 'confirm') {
						btnLeft = document.createElement('button');
						btnLeft.className = 'btnLeft';
						btnRight = document.createElement('button');
						btnRight.className = 'btnRight';
					}
			
					let {
						modalTitle,
						content,
						cancelText,
						okText,
						width,
						onCancel,
						onOkCallBack,
						backgroundColor,
						cancelCallBack,
						isTopRightcancel,
						isCreateOpen
					} = this.options;
			
					modal.className = 'modal';
					modal.style.width = width + 'px';
					modal.style.backgroundColor = backgroundColor;
			
					modalTitleDom.className = 'modalTitle'
					modalTitleDom.innerHTML = `<span class="modalTitleText">${modalTitle}</span>`;
					if (isTopRightcancel) {
						closeIcon = document.createElement('span');
						closeIcon.addEventListener('click', closeModal.bind(this));
						closeIcon.className = 'closeModal';
						modalTitleDom.appendChild(closeIcon);
					}
			
			
			
					main.className = 'main';
					main.innerHTML = content;
					footer.className = 'footer';
					if (type == 'hint') {
						btnOk.innerHTML = '确认';
						footer.appendChild(btnOk);
						onCancel = onCancel ? onCancel : this.closeModal;
						btnOk.addEventListener('click', onCancel.bind(this));
					} else if (type == 'confirm') {
						btnLeft.innerHTML = '取消';
						btnRight.innerHTML = '确认';
						footer.appendChild(btnLeft);
						footer.appendChild(btnRight);
			
						onCancel = onCancel ? onCancel : this.closeModal;
						btnLeft.addEventListener('click', onCancel.bind(this));
						btnRight.addEventListener('click', onOkCallBack);
					}
			
					modal.appendChild(modalTitleDom);
					modal.appendChild(main);
					modal.appendChild(footer);
					modal.className = 'modal';
					this.options.onCancel = onCancel.bind(this);
					document.body.appendChild(modal);
				}
			
				// 关闭弹框
				function closeModal(ev) {
					options.cancelCallBack();
					let target = ev ? ev.path[2] : document.getElementsByClassName('modal')[0];
					let {
						mask
					} = this.options
					mask ? document.body.removeChild(document.querySelector('.mask')) : null;
					document.body.removeChild(target);
				}
			
				
				function openModal() {
					this.init();
				}
			
				// 初始化
				function init() {
					let {
						mask
					} = this.options
					mask ? createMask() : null
					this.createModal(this.options.type);
				}
			
				Modal.prototype.init = init;
				Modal.prototype.createModal = createModal;
				Modal.prototype.closeModal = closeModal;
				Modal.prototype.openModal = openModal;
				// 执行初始化方法
				if (this.options.isCreateOpen) {
					this.init();
					if (this.options.lateRelease) {
						setTimeout(() => {
							let modal = document.getElementsByClassName('modal')[0];
							if(modal){
								this.options.onCancel();
							}
							
						}, this.options.lateReleaseTime);
					}
				}
			}
			

			document.getElementById("btn").addEventListener('click', () => {
				let modal = new Modal({
					lateRelease: true,
					modalTitle: '我是第二个',
					content: `<p>日常开发中,秒杀下单、抢红包等等业务场景,都需要用到分布式锁。而Redis非常适合作为分布式锁使用。本文将分七个方案展开,跟大家探讨Redis分布式锁的正确使用方式。如果有不正确的地方,欢迎大家指出哈,一起学习一起进步。</p>`
				})
				// modal.closeModal();
				// modal.openModal();

			})

完整代码

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
	 
		<title>弹出框</title>
	</head>
	<style type="text/css">
		.mask {
			position: fixed;
			top: 0;
			bottom: 0;
			left: 0;
			right: 0;
			
			background: #bfbfbf;
			opacity: 0.5;
		}

		.modal {
			position: fixed;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			width: 400px;
			background-color: aliceblue;
			border-radius: 5px;
			z-index: 99;
			border: 1px solid rgba(0, 0, 0, 0.2);
		}

		.modal .modalTitle {
			height: 50px;
			box-sizing: content-box;
			display: flex;
			align-items: center;
			justify-content: space-between;
			border-bottom: 2px solid #eeeeee;
			padding: 0 16px;
		}

		.modalTitle .closeModal {
			width: 20px;
			height: 20px;
			border-radius: 5px;
			line-height: 20px;
			text-align: center;
			font-size: 14px;
			cursor: pointer;
			background-image: url('https://typroas.oss-cn-hangzhou.aliyuncs.com/typroaImg/close.png');
			background-size: 100% 100%;

		}


		.modalTitleText {
			margin: 0 auto;
			font-size: 17px;
		}



		.modal .main {
			box-sizing: border-box;
			padding: 16px;
			height: calc(100% - 80px);
		}

		.modal .footer {
			height: 50px;
			text-align: right;
			box-sizing: border-box;
			padding-right: 16px;
			display: flex;
			align-items: center;
			justify-content: flex-end;
		}

		.footer .btnLeft,
		.footer .btnRight {
			width: 120px;
			height: 35px;
			text-align: center;
			line-height: 30px;
			border: none;
			border-radius: 0.2rem;
			margin-left: 8px;
			background-color: #dddddd;
		}

		.footer .btnOk {
			width: 120px;
			height: 35px;
			text-align: center;
			line-height: 30px;
			border: none;
			border-radius: 0.3rem;
			background-color: #1d73d3;
			margin: 0 auto;
			font-size: 17px;
			color: white;
		}

		.footer .btnLeft:hover,
		.footer .btnRight:hover {
			background-color: #1D73D3;
			color: #FFFFFF;
		}
	</style>
	<body>

		<button type="button" id="btn">弹出</button>

		<script type="text/javascript">
			
			function Modal(options) {
				options = Object.assign({
					lateRelease: options.lateRelease ? options.lateRelease : false, //是否开启延时关闭
					lateReleaseTime: options.lateReleaseTime ? options.lateReleaseTime : 5000, // 延时关闭时间
					isCreateOpen: options.isCreateOpen ? options.isCreateOpen : true, //是否创建完毕后就打开弹出框
					type: options.type ? options.type : 'hint', // hint:提示框 confirm:确认框
					isTopRightcancel: true, // 是否需要右上角小x取消按钮
					modalTitle: options.modalTitle ? options.modalTitle : '温馨提示',
					backgroundColor: options.backgroundColor ? options.backgroundColor : '#fff', // 背景颜色
					mask: options.mask ? options.mask : true, //是否显示遮罩层,
					content: options.content ? options.content : '', //弹框内容
					cancelText: options.cancelText ? options.cancelText : '取消', //取消按钮文字
					okText: options.okText ? options.okText : '确认', // 确认按钮文字,
					width: options.width ? options.width : 500, //对话框的宽度
					onCancel: options.onCancel ? options.onCancel : this.closeModal, //取消按钮回调,默认是关闭弹框
					cancelCallBack: options.cancelCallBack ? options.cancelCallBack : () => {
						console.log('你点击了取消');
					}, //取消回调
					onOkCallBack: options.onOkCallBack ? options.onOkCallBack : () => {
						console.log('你点击了确认');
					}, // 确认按钮回调
				}, options);
				this.options = options;
				// 创建遮罩层
				function createMask() {
					let mask = document.createElement('div')
					mask.className = 'mask';
					document.body.appendChild(mask);
				}
			
				// 创建modal弹框
				function createModal(type) {
			
					let modal = document.createElement('div');
					let modalTitleDom = document.createElement('div');
					let main = document.createElement('div');
					let footer = document.createElement('div');
					let btnLeft;
					let btnRight;
					let btnOk;
					let closeIcon;
					if (type == 'hint') {
						btnOk = document.createElement('button');
						btnOk.className = 'btnOk';
					} else if (type == 'confirm') {
						btnLeft = document.createElement('button');
						btnLeft.className = 'btnLeft';
						btnRight = document.createElement('button');
						btnRight.className = 'btnRight';
					}
			
					let {
						modalTitle,
						content,
						cancelText,
						okText,
						width,
						onCancel,
						onOkCallBack,
						backgroundColor,
						cancelCallBack,
						isTopRightcancel,
						isCreateOpen
					} = this.options;
			
					modal.className = 'modal';
					modal.style.width = width + 'px';
					modal.style.backgroundColor = backgroundColor;
			
					modalTitleDom.className = 'modalTitle'
					modalTitleDom.innerHTML = `<span class="modalTitleText">${modalTitle}</span>`;
					if (isTopRightcancel) {
						closeIcon = document.createElement('span');
						closeIcon.addEventListener('click', closeModal.bind(this));
						closeIcon.className = 'closeModal';
						modalTitleDom.appendChild(closeIcon);
					}
			
			
			
					main.className = 'main';
					main.innerHTML = content;
					footer.className = 'footer';
					if (type == 'hint') {
						btnOk.innerHTML = '确认';
						footer.appendChild(btnOk);
						onCancel = onCancel ? onCancel : this.closeModal;
						btnOk.addEventListener('click', onCancel.bind(this));
					} else if (type == 'confirm') {
						btnLeft.innerHTML = '取消';
						btnRight.innerHTML = '确认';
						footer.appendChild(btnLeft);
						footer.appendChild(btnRight);
			
						onCancel = onCancel ? onCancel : this.closeModal;
						btnLeft.addEventListener('click', onCancel.bind(this));
						btnRight.addEventListener('click', onOkCallBack);
					}
			
					modal.appendChild(modalTitleDom);
					modal.appendChild(main);
					modal.appendChild(footer);
					modal.className = 'modal';
					this.options.onCancel = onCancel.bind(this);
					document.body.appendChild(modal);
				}
			
				// 关闭弹框
				function closeModal(ev) {
					options.cancelCallBack();
					let target = ev ? ev.path[2] : document.getElementsByClassName('modal')[0];
					let {
						mask
					} = this.options
					mask ? document.body.removeChild(document.querySelector('.mask')) : null;
					document.body.removeChild(target);
				}
			
				
				function openModal() {
					this.init();
				}
			
				// 初始化
				function init() {
					let {
						mask
					} = this.options
					mask ? createMask() : null
					this.createModal(this.options.type);
				}
			
				Modal.prototype.init = init;
				Modal.prototype.createModal = createModal;
				Modal.prototype.closeModal = closeModal;
				Modal.prototype.openModal = openModal;
				// 执行初始化方法
				if (this.options.isCreateOpen) {
					this.init();
					if (this.options.lateRelease) {
						setTimeout(() => {
							let modal = document.getElementsByClassName('modal')[0];
							if(modal){
								this.options.onCancel();
							}
							
						}, this.options.lateReleaseTime);
					}
				}
			}
			

			document.getElementById("btn").addEventListener('click', () => {
				let modal = new Modal({
					lateRelease: true,
					modalTitle: '我是第二个',
					content: `<p>日常开发中,秒杀下单、抢红包等等业务场景,都需要用到分布式锁。而Redis非常适合作为分布式锁使用。本文将分七个方案展开,跟大家探讨Redis分布式锁的正确使用方式。如果有不正确的地方,欢迎大家指出哈,一起学习一起进步。</p>`
				})
				// modal.closeModal();
				// modal.openModal();

			})
		</script>
	</body>
</html>

以上就是原生JavaScript实现模态框的示例代码的详细内容,更多关于JavaScript模态框的资料请关注编程网其它相关文章!

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-前端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯