如何为弹出窗口设置超时并在用户单击其他位置时关闭?

huangapple go评论70阅读模式
英文:

How to set a timeout for a popup and close if user clicks elsewhere?

问题

我创建了一个弹出窗口,当我点击按钮时它会出现,但要让它消失,我必须再次点击。有没有办法设置一个定时器来让它消失?

功能:

// 当用户点击div时,打开弹出窗口
function myFunction() {
  var popup = document.getElementById("myPopup");
  popup.classList.toggle("show");
}

样式:

.popuptext {
  display: none;
}
.popuptext.show {
  display: block;
}

HTML:

<div class="popup" onclick="myFunction()">点击我切换弹出窗口!
  <span class="popuptext" id="myPopup">一个简单的弹出窗口!</span>
</div>

我需要在10秒后或用户点击其他地方时关闭弹出窗口。

我编辑了代码如下,它确实会在10秒后关闭,如何实现第二部分(当用户点击其他地方时关闭):

function myFunction() {
  var popup = document.getElementById("myPopup");
  popup.classList.toggle("show");
  if (popup.classList.contains("show"))
    setTimeout(() => popup.classList.remove("show"), 10000)
}
英文:

I created a popup that appears when I click a button, but to make it disappear I have to click again. Is there a way to set a timer and make it disappear?

Function:

// When the user clicks on div, open the popup
function myFunction() {
  var popup = document.getElementById(&quot;myPopup&quot;);
  popup.classList.toggle(&quot;show&quot;);
}

Style:

.popuptext {
  display: none;
}
.popuptext.show {
  display: block;
}

The HTML:

&lt;div class=&quot;popup&quot; onclick=&quot;myFunction()&quot;&gt;Click me to toggle the popup!
  &lt;span class=&quot;popuptext&quot; id=&quot;myPopup&quot;&gt;A Simple Popup!&lt;/span&gt;
&lt;/div&gt;

I need the popup to close after 10 seconds OR when the user clicks somewhere else.

I edited the code to below and it does close after 10 seconds, how to achieve the second part (close when user clicks somewhere else):

function myFunction() {
var popup = document.getElementById(&quot;myPopup&quot;);
popup.classList.toggle(&quot;show&quot;);
if(popup.classList.contains(&quot;show&quot;))
    setTimeout(() =&gt; popup.classList.remove(&quot;show&quot;), 10000)
}

答案1

得分: 1

检查点击事件是否发生在popup上。

$('body').click(function(e) {
    if (!$(e.target).closest('.popup').length){

        // 您点击了弹出框外部,编写关闭弹出框的逻辑
        var popup = document.getElementById("myPopup");
        if(popup.classList.contains("show")){
            popup.classList.remove("show")
        }
    }
});
英文:

check with click event occurred not on popup

$(&#39;body&#39;).click(function(e) {
    if (!$(e.target).closest(&#39;.popup&#39;).length){

        // you clicked outside of popup, write your logic to close popup
        var popup = document.getElementById(&quot;myPopup&quot;);
        if(popup.classList.contains(&quot;show&quot;)){
          popup.classList.remove(&quot;show&quot;)
        }
    }
});

答案2

得分: 1

要实现这个,您需要:

  • 定义一个名为hide()的函数,用于隐藏弹出窗口。
  • 为整个document添加一个mousedown事件监听器,调用hide
    • hide函数中,确保点击事件的target不包含在弹出窗口中。
  • 设置超时调用hide
  • 重要提示:确保hide清除创建的超时和移除添加的监听器。
英文:

To do this you need to:

  • Define a function, hide() that hides the popup.
  • Add an mousedown event listener to the whole document that invokes hide
    • Within hide, ensure that the click event's target is not contained in the popup.
  • Set up the timeout to call hide
  • Important: Have hide clear the created timeout and remove the listener that was added.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

function myFunction() {
  var popup = document.getElementById(&quot;myPopup&quot;);
  popup.classList.add(&#39;show&#39;)
  
  let timeout;
  
  function hide(e) {
    if (popup.contains(e.target)) return;

    popup.classList.remove(&quot;show&quot;);
    document.removeEventListener(&#39;mousedown&#39;, hide);
    clearTimeout(timeout)
  }
  document.addEventListener(&#39;mousedown&#39;, hide)
  timeout = setTimeout(hide, 10000)
}

<!-- language: lang-css -->

.popuptext {
  display: none;
}
.popuptext.show {
  display: block;
}

<!-- language: lang-html -->

&lt;div class=&quot;popup&quot; onclick=&quot;myFunction()&quot;&gt;Click me to toggle the popup!
  &lt;span class=&quot;popuptext&quot; id=&quot;myPopup&quot;&gt;A Simple Popup!&lt;/span&gt;
&lt;/div&gt;

<!-- end snippet -->

答案3

得分: 0

我在其他答案中所缺少的是,你正在寻找的东西被称为事件委托

通过将点击事件附加到文档上,你可以使用JavaScript来查看到底点击了什么:

document.addEventListener("click", function(e){
  // 被点击的是什么?
  const elementClicked = e.target.id;
});

现在你可以对其进行操作:

document.addEventListener("click", function(e){
  // 被点击的是什么?
  const elementClicked = e.target.id;

  if(elementClicked == 'your_button')
  {
    // 点击了你的按钮。为用户弹出模态框并设置定时器。
  }
  else
  {
    // 点击了其他东西。如果存在弹出框,则关闭它。禁用定时器。
  }

});

你看到事件委托的威力了吗?现在你可以捕获任何点击,无论是什么,然后根据它是什么来执行某些操作。

英文:

What I'm missing in the other answers is that what you're looking for is called Event Delegation.

By attaching a click event to your document, you can use Javascript to see what exactly has been clicked:

document.addEventListener(&quot;click&quot;, function(e){
  // What has been clicked?
  const elementClicked = e.target.id;
});

Now you can work with it:

document.addEventListener(&quot;click&quot;, function(e){
  // What has been clicked?
  const elementClicked = e.target.id;

  if(elementClicked == &#39;your_button&#39;)
  {
    // Your button is clicked. Popup your modal for the user and set the timer.
  }
  else
  {
    // Something else was clicked. Close the popup IF it exists. Disable the timer.
  }

});

You see the power of event delegation? You can now catch any click, regardless of what it is, and do something with it, depending on what it is.

答案4

得分: -1

第一种方式

&lt;html&gt;
  &lt;body&gt;
    &lt;div id=&quot;flyout-example&quot;&gt;
      &lt;h5&gt;这可能是一个弹出窗口;&lt;/h5&gt;
      &lt;div id=&quot;flyout-debug&quot;&gt;&lt;/div&gt;
      &lt;div&gt;
        &lt;button class=&quot;button button-outline&quot; type=&quot;button&quot;&gt;取消&lt;/button&gt;
        &lt;button class=&quot;button&quot; type=&quot;button&quot;&gt;确定&lt;/button&gt;
      &lt;/div&gt;
    &lt;/div&gt;
    &lt;script&gt;
      document.addEventListener(&quot;click&quot;, (evt) =&gt; {
        const flyoutEl = document.getElementById(&quot;flyout-example&quot;);
        let targetEl = evt.target; // 点击的元素      
        do {
          if(targetEl == flyoutEl) {
            // 这是内部点击,什么都不做,只是返回。
            document.getElementById(&quot;flyout-debug&quot;).textContent = &quot;点击了内部!&quot;;
            return;
          }
          // 向上遍历DOM
          targetEl = targetEl.parentNode;
        } while (targetEl);
        // 这是外部点击。      
        document.getElementById(&quot;flyout-debug&quot;).textContent = &quot;点击了外部!&quot;;
      });
    &lt;/script&gt;
  &lt;/body&gt;
&lt;/html&gt;

第二种方式

$(window).click(function () { // 如果可见,隐藏菜单 }); 
  

如果弹出窗口在点击时关闭请使用 `stopPropagation`

```javascript
$(&#39;#menucontainer&#39;).click(function (event) {event.stopPropagation();});
英文:

you can achieve this in two different ways

First

&lt;html&gt;
  &lt;body&gt;
    &lt;div  id=&quot;flyout-example&quot;&gt;
      &lt;h5 &gt;This could be a flyout;&lt;/h5&gt;
      &lt;div id=&quot;flyout-debug&quot;&gt;&lt;/div&gt;
      &lt;div&gt;
        &lt;button class=&quot;button button-outline&quot; type=&quot;button&quot;&gt;Cancel&lt;/button&gt;
        &lt;button class=&quot;button&quot; type=&quot;button&quot;&gt;Ok&lt;/button&gt;
      &lt;/div&gt;
    &lt;/div&gt;
    &lt;script&gt;
      document.addEventListener(&quot;click&quot;, (evt) =&gt; {
        const flyoutEl = document.getElementById(&quot;flyout-example&quot;);
        let targetEl = evt.target; // clicked element      
        do {
          if(targetEl == flyoutEl) {
            // This is a click inside, does nothing, just return.
            document.getElementById(&quot;flyout-debug&quot;).textContent = &quot;Clicked inside!&quot;;
            return;
          }
          // Go up the DOM
          targetEl = targetEl.parentNode;
        } while (targetEl);
        // This is a click outside.      
        document.getElementById(&quot;flyout-debug&quot;).textContent = &quot;Clicked outside!&quot;;
      });
    &lt;/script&gt;
  &lt;/body&gt;
&lt;/html&gt;

Second

$(window).click(function () { //Hide the menus if visible }); 

if popup is getting close when clicking on it use stopPropogation

$(&#39;#menucontainer&#39;).click(function (event) {event.stopPropagation();});

huangapple
  • 本文由 发表于 2023年6月1日 20:13:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76381742.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定