You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript新手求助:如何实现弹窗表单仅显示一次

How to Make Your Popup Form Show Only Once in JavaScript

Hey there! Since you're new to JavaScript, let's walk through a simple, reliable way to make that popup form appear only once for each user. This is a super common feature, and we'll use localStorage—a built-in browser tool that saves small pieces of data between sessions—to pull it off.

First, Make Sure Your Popup is Hidden by Default

First, add some CSS to keep the popup and overlay hidden when the page loads (you probably already have this, but just in case):

.backgroundOverlay, .delayedPopupWindow {
  display: none;
  /* Add your existing styling here—like semi-transparent background, centered positioning, etc. */
}

The JavaScript Logic

Next, add this script to your page (either at the end of the <body> tag, or wrapped in a DOMContentLoaded listener to make sure elements load first):

document.addEventListener('DOMContentLoaded', function() {
  // Grab your popup elements from the DOM
  const overlay = document.getElementById('bkgOverlay');
  const popup = document.getElementById('delayedPopup');

  // Check if we've already shown the popup before
  const popupHasShown = localStorage.getItem('hasSeenPopup');

  if (!popupHasShown) {
    // If it's the first visit, show the popup
    overlay.style.display = 'block';
    popup.style.display = 'block';

    // Save a flag to localStorage so we don't show it again
    localStorage.setItem('hasSeenPopup', 'true');
  }

  // Add a way to close the popup (clicking the overlay, for example)
  overlay.addEventListener('click', function() {
    overlay.style.display = 'none';
    popup.style.display = 'none';
  });

  // If you have a close button in your popup, add this too:
  // const closeButton = document.querySelector('#delayedPopup .close-btn');
  // closeButton.addEventListener('click', function() {
  //   overlay.style.display = 'none';
  //   popup.style.display = 'none';
  // });
});

What's Happening Here?

  • localStorage.getItem('hasSeenPopup') checks if we've stored a flag indicating the popup was already shown.
  • If the flag doesn't exist (meaning it's the user's first visit), we show the popup and save the flag to localStorage.
  • From then on, every time the user loads the page, the script will see the flag and skip showing the popup.

Bonus: Session-Only Popup

If you want the popup to reset when the user closes their browser (instead of being permanent), replace localStorage with sessionStorage in the code above. That way, the popup will show again when the user opens a new browser session.

内容的提问来源于stack exchange,提问作者Ben

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:12:45