简体   繁体   English

如何使用JavaScript制作关闭按钮?

[英]How to make a close button with JavaScript?

I am starting with JS and I would like to make the close button close the div .popup1 on this code: 我从JS开始,我想使关闭按钮关闭此代码上的div .popup1:

https://jsfiddle.net/74hmx0vb/1 https://jsfiddle.net/74hmx0vb/1

<div class='popup1' id="popup1">
  <div class="container">
    <div class="row rowpopup">
      <div class="iconpopup">
        <img class="imgpopup" src="" />
      </div>
      <div class="textpopup">
        <div class="textpopup1">

        </div>
        <div class="textpopup2">

        </div>
      </div>
      <button type="button" class="close" aria-label="Close">
        <span aria-hidden="true">&times;</span>
      </button>
    </div>
  </div>
</div>

I guess the best option is to make the close button call a function on click that adds a class with display: none, is that right? 我猜最好的选择是使关闭按钮在单击时调用一个函数,该函数添加带有显示的类:无,对吗? I would also like to add a fadeout transition when the close button is clicked. 单击关闭按钮时,我还想添加一个淡入淡出过渡。

How to do that? 怎么做? Is there any other better option? 还有其他更好的选择吗?

That's right a function that applies a class would work as you are looking for in this case you can have a function that applies a class when the close button is clicked like: 没错,一个应用类的函数将在您要查找的情况下起作用,在这种情况下,您可以拥有一个在单击关闭按钮时应用类的函数,例如:

var popupEl = document.querySelector( '. popup1' );
var button = document.querySelector( '.close' );

button.addEventListener( 'click', function() {
   popupEl.classList.add( 'closed' );
});

So your DOM will change into something like: 因此,您的DOM将变为:

<div class='popup1 closed' id="popup1">
....

In that sense you can use opacity to hide and apply a transition into your element like: 从这种意义上讲,您可以使用不透明度来隐藏元素并将其应用到元素中,例如:

.popup {
   opacity: 1;
   transition: opacity 0.5s ease-out;
}

.closed {
   opacity: 0;
}

One last thing is that this will keep the element visible just with a hidden opacity, in order to remove it from the DOM or hide it completely you can use transitionend to listen when the opacity transition has completed like: 最后一件事是,这将使元素仅在具有隐藏的不透明度的情况下可见,为了将其从DOM中删除或完全隐藏,可以在不透明度转换完成时使用transitionend进行监听,例如:

popupEl.addEventListener( 'transitionend', function(){
   popupEl.classList.add( 'removed ');
});

// css
.removed {
   display: none;
}

Be aware that transitionend will run in both directions it means on closed applied or removed so you need to make sure you are applying the removed class only when closed class is present on the element like: 请注意, transitionend会在两个方向上运行,这意味着在closed或已closed应用或已移除,因此您需要确保仅在元素上存在closed类时才应用已removed类:

popupEl.addEventListener( 'transitionend', function(){
   if( popupEl.classList.contains( 'closed' ) ) {
   popupEl.classList.add( 'removed ');
}
});

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

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