繁体   English   中英

自动添加类,并在关闭菜单或单击主体时将其删除

[英]Automatic Add class and remove it when menu is close or body click to body

早上好,老实说,我不知道如何正确地使用js,从学校开始学习。 单击带有类menuToggle的菜单后,下面的代码会menuToggle modal-backdrop 我要完成的是再次单击或关闭菜单后,该类模态背景也会被删除。

下面的代码只是将模式背景div广告化,并在10秒或更长时间后自动删除。

$("a.menuToggle").click(function() {
  var bd = $('<div class="modal-backdrop"></div>');
  bd.appendTo(document.body);
  setTimeout(function() {
    bd.remove();
  }, 10000);
});

像这样:

   $("a.menuToggle").click(function() {
        if($('.modal-backdrop').length) {
            $(this).removeClass('.modal-backdrop');
        } else {
            var bd = $('<div class="modal-backdrop"></div>');
            bd.appendTo(document.body);
        }
    });

有多种方法可以实现此目的,您可以使用classList toggle()方法来切换删除opacityz-index以“隐藏”模态。

您也可以在JS中创建弹出模式,然后再将其附加到接口上,只需设置一个事件侦听器以在单击时将其自身删除即可。

 init=()=>{ //SELECT & BIND (CLICK) EVENT document.querySelector('login').addEventListener('click',modal.overlay.init); } modal={ overlay:{ init:()=>{ //CREATE OVERLAY var overlay = document.createElement('overlay'); //SET (CLICK) EVENT TO REMOVE ITSLEF overlay.addEventListener('click',modal.overlay.remove); //APPEND TO INTERFACE document.body.appendChild(overlay); }, remove:(e)=>{ //REMOVE ITSELF e.target.parentNode.removeChild(e.target); } } } //ON DOCUMENT LOAD RUN INIT document.addEventListener('DOMContentLoaded',init); 
 html{ height: 100%; width: 100%; } html *{ box-sizing: border-box; -webkit-font-smoothing: antialiased; /* DISABLE USER SELECT */ -moz-user-select: none; -webkit-user-select: none; -ms-user-select: none; } body{ z-index: 100; margin: 0 !important; height: 100%; width: 100%; display: flex; flex-direction: column; justify-content: center; align-items: center; background: -webkit-radial-gradient(#41a3ff,#0273D4); } login{ position: relative; margin: 1em 0 0 0; padding: .25em 1.5em; display: flex; justify-content: center; align-items: center; cursor: pointer; color: #0273D4; border-width: 1px; border-style: solid; border-color: #0273D4; text-transform: capitalize; font-family: Roboto, sans-serif; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } login:hover{ color: white; border-color: white; /* background-color: rgba(255, 255, 255, 0.31); */ -webkit-box-shadow: 0px 2px 7px rgba(0, 0, 0, 0.40); box-shadow: 0px 2px 7px rgba(0, 0, 0, 0.40); } login:active{ -webkit-box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15) inset; -moz-box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15) inset; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15) inset; } overlay{ position: absolute; top: 0; left: 0; display: flex; height: 100vh; width: 100vw; justify-content: center; flex-direction: column; align-items: center; background-color: rgba(0, 0, 0, 0.8); } 
 <body> <login>click me</login> </body> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM