首页 > 解决方案 > 单击屏幕上的任意位置以隐藏没有 Jquery 的通知栏

问题描述

我实际上正在研究一个 Ionic 3 项目,但它可能是我实际面临的问题的任何 Javascript 框架:

根据单击时出现的自定义通知栏(屏幕右上角),您实际上可以关闭该通知栏,再次单击同一个按钮,但这种方式的用户体验真的很糟糕。

我想要的:用户可以点击屏幕上的任意位置来隐藏通知栏

我知道如何在 jquery 中做到这一点,但我不想在该项目中使用它:

通知.html:

  <ion-button (click)="toggleNotifications()">
    <div class="notif-button" id="notif-button"></div>
  </ion-button>

notif.ts(jQuery 方式):

$('#notif-button').click(function(e){
  e.stopPropagation();
  $('#hide-notif').toggleClass('show-notif');
});

$('#hide-notif').click(function(e){
  e.stopPropagation();
});

$('body,html').click(function(e){
 $('#hide-notif').removeClass('show-notif');
});

标签: javascripthtmltypescriptionic-frameworkionic3

解决方案


<ion-button (click)="toggleNotifications()">
    <div class="notif-button" id="notif-button"></div>
</ion-button>


<script>
// Get the modal
var modal = document.getElementById('notif-button');

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}
</script>

推荐阅读