Home > Web Front-end > Front-end Q&A > How to use JavaScript to achieve the effect of closing on a second click

How to use JavaScript to achieve the effect of closing on a second click

PHPz
Release: 2023-04-26 15:12:01
Original
809 people have browsed it

With the continuous development of front-end technology, websites are becoming more and more interactive, and more and more websites need to use JavaScript to achieve various effects. Among them, click events are the most common, and in some websites, there are more and more cases where you need to click again to close after clicking. So, the question is, how to achieve the second close effect of JavaScript click?

1. Basic idea

It is not difficult to achieve the second close effect of JavaScript click. The basic idea is as follows:

1. Monitor the click event and add up each click. Number of clicks;

2. When the number of clicks reaches the specified number, perform the closing operation.

2. Implementation

Let’s implement this function through an example.

  1. HTML part
<body>

  <h1>JavaScript点击第二次关闭</h1>

  <p>这是一个演示点击第二次关闭的效果的实例。</p>

  <button id="closeBtn">关闭</button>

  <script src="main.js"></script>

</body>
Copy after login
  1. JavaScript part
var closeBtn = document.getElementById("closeBtn");
var clickCount = 0;

closeBtn.onclick = function() {
  clickCount++;
  
  if (clickCount == 2) {
    window.close();
  }
};
Copy after login
  1. CSS part (optional)
button {
  background-color: #4CAF50;
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 10px;
  cursor: pointer;
}
Copy after login

3. To achieve the effect

When the button is clicked once, the window will not be closed;

When the button is clicked twice, the window will be automatically closed.

4. Notes

1. The click event can be a button, hyperlink, etc.;

2. The number of clicks can be specified as any number;

3. The closing operation can be any operation, such as closing the web page, hiding the button, etc.

In short, according to actual needs and flexible use of basic ideas, the effect of JavaScript closing for the second time can be achieved.

The above is the detailed content of How to use JavaScript to achieve the effect of closing on a second click. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template