2022年9月27日

不用layui,用原生js写的打开弹窗和关闭效果


应一个网站切图的需要,要求不能用jquery,因为会和原系统冲突,既然不能用jquery那自然layui的layer弹窗框架也用不了了(layui是基于jquery的),于是用原生js简单模拟layer方式写了个效果。

不得不说原生js写代码的确没有jquery优雅,而且原生js实现动画效果比较困难,所以没有加入过渡动画,只是实现了弹窗的基本效果。

附不用layer,原生js写的打开弹窗和关闭代码,亲测可用

调用代码


<li><a class="showlink" onclick="openLayer('show1.html')" ><span>壹</span>大时代的国民烟</a></li>
<li><a class="showlink" onclick="openLayer('show2.html')" ><span>贰</span>“玉溪”大家族</a></li>
<li><a class="showlink" onclick="openLayer('show3.html')" ><span>叁</span>“玉溪”20年</a></li>

<div class="closebtn" onclick="closeLayer()"></div>

html代码


<div id="layer">
<div id="layermask"></div>
<iframe src="" id="layeriframe"></iframe>
</div>

css代码


#layer{
position: fixed; left: 0; right: 0; top: 0; bottom: 0; overflow-y: scroll;
display: none; z-index: 9;
}
#layer iframe{
width: 100%; height: 100%; position: relative; border: none;

}
#layermask{
position: absolute; left: 0; right: 0; top: 0; bottom: 0;
background: rgba(0,0,0,0.5);
}

js代码


function openLayer(url){

//document.querySelectorAll(".bb")[index].style.color = "red";

document.getElementById('layeriframe').src= url;
document.getElementById('layer').style.display='block';
document.getElementsByTagName('body')[0].style = 'overflow:hidden';
document.getElementsByTagName('html')[0].style = 'overflow:hidden';
}
function closeLayer(event){

window.parent.document.getElementById('layer').style.display='none';
window.parent.document.getElementsByTagName('body')[0].style = 'overflow:auto';
window.parent.document.getElementsByTagName('html')[0].style = 'overflow:auto';
}

标签:,

微信扫一扫二维码访问