This HTML file sets up a basic structure with a container holding control buttons and a countdown display area.

Implementing countdown logic using JavaScript

Next, we\\'ll add JavaScript to manage the countdown logic. Add the following code to index.js:

window.addEventListener(\\\"load\\\", () => {  const startBtn = document.getElementById(\\'startBtn\\');  const pauseBtn = document.getElementById(\\'pauseBtn\\');  const countdownView = document.getElementsByClassName(\\'countdown\\')[0];  let totalTime = 10;  let timeLeft;  let countDownIntervalID;  let isPaused = false;  pauseBtn.style.display = \\'none\\';});  

In this block of code, we initialize the startBtn, pauseBtn, and countdownView elements by their respective IDs and classes. We also set some initial variables: totalTime, timeLeft, countDownIntervalID, and isPaused. Additionally, we set the pause button to hide initially.

Now, let\\'s add event listeners for the start and pause buttons:

startBtn.addEventListener(\\'click\\', startOrStopTimer);pauseBtn.addEventListener(\\'click\\', pauseOrResumeTimer);

These lines attach click event listeners to the start and pause buttons. The functions startOrStopTimer and pauseOrResumeTimer are defined later to handle the button clicks.

Add the following code to define the startOrStopTimer function:

function startOrStopTimer() {  startBtn.innerHTML = startBtn.innerHTML === \\'Start\\' ? \\'Stop\\' : \\'Start\\';  if (countDownIntervalID === undefined && !isPaused) {    timeLeft = totalTime;    startTimer();    pauseBtn.style.display = \\'inline\\';  } else {    stopTimer();    countdownView.innerHTML = \\'\\';    pauseBtn.style.display = \\'none\\';    isPaused = false;    pauseBtn.innerHTML = \\'Pause\\';  }}

In this function, we toggle the start button text between Start and Stop. If the countdown is not running and not paused, we initialize timeLeft to totalTime and start the timer. Otherwise, we stop the timer and reset the view.

Now, define the startTimer function:

function startTimer() {  countDownIntervalID = setInterval(() => {    countdownView.innerHTML = timeLeft;    if (timeLeft === 0) {      stopTimer();      startBtn.innerHTML = \\'Start\\';      pauseBtn.style.display = \\'none\\';      countdownView.innerHTML = \\'\\';    } else {      timeLeft = timeLeft - 1;    }  }, 1000);}

This function sets an interval to update the countdown every second. If timeLeft reaches zero, we stop the timer, reset the start button text, and hide the pause button.

Next, add the stopTimer function:

function stopTimer() {  if (countDownIntervalID !== undefined) {    clearInterval(countDownIntervalID);    countDownIntervalID = undefined;  }}

This function clears the countdown interval and resets countDownIntervalID. Finally, add the pauseOrResumeTimer function:

function pauseOrResumeTimer() {  isPaused = !isPaused;  pauseBtn.innerHTML = isPaused ? \\'Resume\\' : \\'Pause\\';  if (countDownIntervalID !== undefined) {    stopTimer();  } else {    startTimer();  }}

In this function, we toggle the pause state and button text between Pause and Resume. If the countdown is running, we stop the timer; otherwise, we start it again.

CSS styling

Now, let\\'s style the countdown timer using CSS. Add the following code to styles.css:

body {  background-color: black;  font-family: Arial, sans-serif;  height: 100%;}.container {  display: flex;  flex-direction: column;  justify-content: center;  align-items: center;}.controls {  width: 20%;  margin-top: 10%;  display: flex;  justify-content: space-between;  flex-direction: row;  flex-wrap: wrap;}.countdown-container {  position: relative;  width: 20vw;  height: 20vw;  margin-top: 2%;  border: 0.4em solid #9b51e0;}button {  font-size: 1.5em;  border: none;  padding: 0.3em;  background-color: #9b51e0;  border-radius: 0.4em;  color: white;}.countdown {  position: relative;  width: 100%;  height: 100%;  list-style: none;  padding: 0;  margin: 0;  display: flex;  justify-content: center;  align-items: center;  font-size: 5em;  color: #9b51e0;}

This CSS defines styles for the countdown timer interface. The body background is set to black, and we use Arial as the primary font. The .container class is styled to center its contents and provide spacing between elements. The .controls class styles the buttons for starting and pausing the timer, ensuring they are evenly spaced and responsive. The .countdown-container class defines the size and appearance of the countdown display, including a border and margin.

Go back to your terminal and run the following command to start serving the JavaScript countdown application:

node server.js

Open a new tab in your browser, navigate to http://localhost:3001, and you should see something similar to the following: \\\"How Test out the countdown timer and once you are done, terminate the server application and move to the next step.

Adding a circular progress indicator

To enhance the user experience of our countdown timer, let’s add a circular progress indicator to give the user a visual representation of the time remaining.

First, we need to modify our HTML code to include the circular progress element. In index.html, we add a span element with a class of circular-progress inside the countdown-container div. This span element will be used to create the circular progress indicator:

Next, we need to define the CSS for the circular progress indicator. In styles.css, we add the following code:

.countdown-container {  ...  /* border : 0.4em solid #9b51e0; */}.circular-progress {  width: 20vw;  height: 20vw;  border-radius: 50%;  display: flex;  justify-content: center;  align-items: center;  position: absolute;  transition: 0.5s;  background-color: #13171f;}.circular-progress::before {  width: 18.5vw;  height: 18.5vw;  content: \\\"\\\";  position: absolute;  border-radius: 50%;  background-color: black;}

This code first removes the border from the countdown-container div, then sets the dimensions and shape of the circular progress indicator, as well as its position and background color. We also add a ::before pseudo-element to create the inner circle of the progress indicator.

Now we need to add the JavaScript code to animate the circular progress indicator.

Add the following code in the variables initialization block:

const circularProgressEl = document.getElementsByClassName(\\\"circular-progress\\\")[0];let circularProgress;let circularProgressIntervalID;

This code initializes the circularProgressEl variable to target the circular progress element and creates two new variables, circularProgress and circularProgressIntervalID, that will be used to animate the progress indicator.

Add the following code below the pauseOrResumeTimer() function:

function startCircularProgressAnimation() {  let start = totalTime - timeLeft;  let degreesPerSecond = 360 / totalTime;  let degreesPerInterval = degreesPerSecond / 20;  circularProgress = degreesPerSecond * start;   circularProgressIntervalID = setInterval(() => {    if (Math.round(circularProgress) === 360) {      clearInterval(circularProgressIntervalID);    } else {      circularProgress = circularProgress   degreesPerInterval;      circularProgressEl.style.background = `conic-gradient(#9b51e0 ${circularProgress}deg, #13171f 0deg)`;    }  }, 50);}

This code defines the startCircularProgressAnimation function, which calculates the starting point and degree of rotation for the circular progress indicator, and sets up an interval to animate the progress indicator.

Add the following code below the startCircularProgressAnimation:

function resumeCircularProgressAnimation() {  startCircularProgressAnimation();}function pauseCircularProgressAnimation() {  clearInterval(circularProgressIntervalID);}function stopCircularProgressAnimation() {  clearInterval(circularProgressIntervalID);  circularProgressEl.style.background = `conic-gradient(#9b51e0 0deg, #13171f 0deg)`;}

This code defines the resumeCircularProgressAnimation, pauseCircularProgressAnimation, and stopCircularProgressAnimation functions, which are used to start, pause, and stop the circular progress animation.

Finally, we need to modify the startOrStopTimer and pauseOrResumeTimer functions to start and stop the circular progress animation along with the timer:

function startOrStopTimer() {  // ...  if (countDownIntervalID === undefined && !isPaused) {    // ...    startCircularProgressAnimation();  } else {    // ...    stopCircularProgressAnimation();  }}function pauseOrResumeTimer() {  // ...  if (countDownIntervalID !== undefined) {    stopTimer();    pauseCircularProgressAnimation();  } else {    startTimer();    resumeCircularProgressAnimation();  }}

With these modifications, our countdown timer now includes a circular progress indicator that animates along with the timer.

Return to your terminal and run the following command to start serving the JavaScript countdown application:

node server.js

Go back to the tab in your browser where you visited the http://localhost:3001 URL, refresh the page, and you should see something similar to the following: \\\"How

Implementing a CSS-only countdown timer

In this section, we\\'ll dive into creating a countdown timer that updates every second and is made using only CSS. Our timer will be simple yet functional, featuring start and pause buttons to control its operation.

Creating the application server

Navigate to the css-only-countdown subdirectory, initialize a new node project, and install the express package:

cd ../css-only-countdownnpm init -ynpm install express

Then, return to your text editor, create a file named server.js, and add the following code to it:

const express = require(\\'express\\');const app = express();const port = 3002app.use(express.static(\\'public\\'));app.listen(port, () => {  console.log(`Css-only countdown app server started on port ${port}`);});

The code above creates an express server that will be used to serve the JavaScript countdown application in port 3002.

HTML structure

Still in your text editor, create the following files in the public subdirectory:

Add the following code to the index.html file:

        CSS Countdown Timer  
  • 10
  • 9
  • 8
  • 7
  • 6
  • 5
  • 4
  • 3
  • 2
  • 1

This code sets up the basic structure of our countdown timer. It includes a container div that holds the controls for starting and pausing the timer, as well as the countdown display itself. The controls div contains two checkboxes with labels that will serve as our start and pause buttons. These buttons toggle their respective states using CSS, thanks to the checkbox hack.

The countdown-container div holds an unordered list (ul) of list items (li) representing the countdown numbers from 10 to one. These numbers will be displayed one by one as the timer counts down.

CSS styling

Now, let\\'s style the countdown timer using CSS. Add the following code to styles.css:

body {  background-color: black;  font-family: Arial, sans-serif;  height: 100%;}.container {  display: flex;  flex-direction: column;  justify-content: center;  align-items: center;}.controls {  width: 20%;  margin-top: 10%;  display: flex;  justify-content: space-between;  flex-direction: row;  flex-wrap: wrap;}.countdown-container {  position: relative;  width: 20vw;  height: 20vw;  margin-top: 12%;  border : 0.4em solid #9b51e0;}#startLabel span {  display: none;}label {  cursor: pointer;  font-size: 1.5em;  padding: 0.3em;  background-color: #9b51e0;  border-radius: 0.4em;  color: white;}#startBtn:checked~#startLabel span:nth-child(1) {  display: inline;}#startBtn:not(:checked)~#startLabel span:nth-child(2) {  display: inline;}#startBtn:not(:checked)~#pauseLabel,#pauseBtn {  display: none;}#pauseLabel span {  display: none;}#pauseBtn:checked~#pauseLabel span:nth-child(1) {  display: inline;}#pauseBtn:not(:checked)~#pauseLabel span:nth-child(2) {  display: inline;}.checkbox-wrapper {  display: none;}

In this CSS file, we start by setting some basic styles for the body and container. The body has a black background and uses the Arial font. The container is centered using flexbox and has a margin to push it down from the top of the viewport.

The controls div is styled to be responsive and to ensure that the buttons are spaced out evenly. The countdown-container div is styled with a border, which will later be replaced by the circular progress indicator.

We use the checkbox hack to toggle the visibility of the labels for the start and pause buttons. Depending on whether the checkboxes are checked or not, different spans within the labels are displayed. This allows the labels to show different text (Start or Stop, Pause or Resume) based on the state of the checkboxes.

Now, add the following code to the bottom of the styles.css file:

.countdown {  position: relative;  width: 100%;  height: 100%;  list-style: none;  padding: 0;  margin: 0;  display: flex;  justify-content: center;  align-items: center;  font-size: 5em;  color: #9b51e0;}.countdown li {  position: absolute;  opacity: 0;  transition: opacity 1s linear;}#startBtn:checked~.countdown-container .countdown li:nth-child(1) {  animation-delay: 0s;}#startBtn:checked~.countdown-container .countdown li:nth-child(2) {  animation-delay: 1s;}#startBtn:checked~.countdown-container .countdown li:nth-child(3) {  animation-delay: 2s;}#startBtn:checked~.countdown-container .countdown li:nth-child(4) {  animation-delay: 3s;}#startBtn:checked~.countdown-container .countdown li:nth-child(5) {  animation-delay: 4s;}#startBtn:checked~.countdown-container .countdown li:nth-child(6) {  animation-delay: 5s;}#startBtn:checked~.countdown-container .countdown li:nth-child(7) {  animation-delay: 6s;}#startBtn:checked~.countdown-container .countdown li:nth-child(8) {  animation-delay: 7s;}#startBtn:checked~.countdown-container .countdown li:nth-child(9) {  animation-delay: 8s;}#startBtn:checked~.countdown-container .countdown li:nth-child(10) {  animation-delay: 9s;}@keyframes countdownAnimation {  0%,  10% {    opacity: 1;  }  11%,  100% {    opacity: 0;  }}#startBtn:checked~.countdown-container .countdown li {  animation: countdownAnimation 10s steps(10) forwards;}#pauseBtn:checked~.countdown-container .countdown li {  animation-play-state: paused;}

With this code, we style the countdown list. The countdown class is positioned absolutely within the countdown-container, and its list items are initially hidden with opacity: 0.

We then use keyframes and the animation property to create the countdown effect. The list items are displayed one by one with a delay using the animation-delay property. The countdownAnimation keyframes control the visibility of each list item, making them visible for a short period before hiding them again.

We also pause the animation when the pause button is checked, using the animation-play-state property.

Go back to your terminal and run the following command to start serving the CSS-only countdown application:

node server.js

Open a new tab in your browser, navigate to http://localhost:3002 URL, and you should see something similar to the following: \\\"How Test out the countdown timer and once you are done, terminate the server application and move to the next step.

Adding a circular progress indicator

To make the countdown timer more visually appealing, we can add a circular progress indicator that shows the remaining time. To do this, we will modify the HTML and CSS code as follows:

First, replace the countdown-container div in the index.html file with the following code:

In this code, we add a span element with a class of circular-progress inside the countdown-container div.

Next, add the following code to the styles.css file:

.countdown-container {  ...  /* border : 0.4em solid #9b51e0; */}.circular-progress {  width: 20vw;  height: 20vw;  border-radius: 50%;  display: flex;  justify-content: center;  align-items: center;  position: absolute;  transition: 0.5s;  background: conic-gradient(#9b51e0 var(--angle), #13171f 0deg);}.circular-progress::before {  width: 18.5vw;  height: 18.5vw;  content: \\\"\\\";  position: absolute;  border-radius: 50%;  background-color: black;}@keyframes circularProgressAnimation {  to {    --angle: 360deg;  }}@property --angle {  syntax: \\\"\\\";  initial-value: 0deg;  inherits: false;}#startBtn:checked~.countdown-container .circular-progress {  opacity: 1;  animation: circularProgressAnimation 10s linear;}#pauseBtn:checked~.countdown-container .circular-progress {  animation-play-state: paused;}

In this code, we first remove the border from the countdown-container div, and then add styles for the circular-progress class. The circular progress indicator is a span element that is absolutely positioned within the countdown-container. It uses a conic gradient to create the circular progress effect.

We also define a keyframe animation, circularProgressAnimation, that animates the progress indicator from 0 to 360 degrees over the duration of the countdown. The --angle CSS property is used to control the angle of the gradient.

Finally, we use the checkbox hack to start and pause the circular progress animation along with the countdown numbers. The animation is applied to the circular-progress span when the start button is checked and paused when the pause button is checked.

With these modifications, our countdown timer now includes a circular progress indicator that animates along with the timer.

Go back to your terminal and run the following command to start serving the CSS-only countdown application:

node server.js

Return to the tab in your browser where you visited the http://localhost:3002 URL, refresh the page, and you should see something similar to the following: \\\"How

Using Chrome DevTools to compare timer performance

Now that we have implemented both the CSS-only and JavaScript countdown timers, let\\'s compare their performance using Chrome DevTools.

To get started, open the Chrome browser and navigate to the webpage containing the countdown timers. Right-click anywhere on the page and select Inspect to open Chrome DevTools.

In the DevTools window, click on the Network tab and then refresh both the JavaScript and CSS-only countdown pages. This tab allows you to monitor all network requests made by the page, including HTML, CSS, JavaScript, and other resources: \\\"How

By analyzing the requests, you can determine how many resources are being loaded, their sizes, and the overall impact on page load time:

CSS-only countdown timerJavaScript countdown timer
Number of requests23
Total size4.5 KB4.7 KB
Page load24 ms27 ms

From these results, we can see that the CSS-only countdown timer requires fewer requests and has a slightly smaller total size compared to the JavaScript countdown timer. This leads to a marginally faster page load time for the CSS-only version, making it more efficient in terms of initial loading.

Now, in the DevTools window, navigate to the Performance tab and initiate a recording session by clicking on the Record button. To evaluate the JavaScript countdown timer, click on the Start button located on its respective page and allow the timer to run its course. Once the timer has stopped, cease the recording in the Performance tab.

Do this process for both the JS and CSS-only countdown pages to gather performance data for each implementation. The Performance tab offers a comprehensive analysis of your page\\'s runtime performance, encompassing scripting, rendering, and painting times. By analyzing these metrics, you can pinpoint areas that may require optimization to enhance the performance of your web application:

CSS-only countdown timerJavaScript countdown timer
Scripting2 ms49 ms
Rendering510 ms103 ms
Painting275 ms55 ms

Interpreting these results, we observe that the scripting time for the CSS-only countdown timer is significantly lower than for the JavaScript countdown timer, indicating minimal execution overhead. However, the CSS-only countdown timer has higher rendering and painting times. This is because CSS animations can sometimes require more effort from the browser to render, especially for complex styles or transitions.

In contrast, the JavaScript countdown timer shows higher scripting time due to the logic involved in updating the countdown, but it benefits from lower rendering and painting times. This suggests that while JavaScript adds some overhead in terms of script execution, it can be more efficient in terms of updating the DOM and rendering changes.

Overall, the CSS-only countdown timer is more efficient for scenarios where minimizing script execution time is critical, whereas the JavaScript timer may perform better in cases where rendering and painting times are the primary concern.

Pros and cons of each approach

Having explored both the CSS-only and JavaScript countdown timers, let\\'s weigh their advantages and disadvantages to determine which approach best suits your needs.

CSS-only countdown timer

The CSS-only countdown timer leverages pure CSS to achieve the countdown effect, providing a lightweight and straightforward solution.

Its pros include the following:

Cons to this approach include:

JavaScript countdown timer

The JavaScript countdown timer, on the other hand, uses JavaScript to manage the countdown logic and DOM updates. This approach offers greater control and flexibility.

Pros of this approach include:

Cons include:

The CSS-only timer is lightweight and easy to understand, making it a good choice for simple countdowns with minimal scripting. However, it may struggle with more complex animations and interactive features. On the other hand, the JavaScript timer offers greater control and flexibility, allowing for more dynamic interactions. This comes at the cost of higher scripting overhead and increased complexity.

Ultimately, the choice between the two approaches depends on the specific needs of your project and the trade-offs you are willing to accept.

Conclusion

In this tutorial, we explored two methods for creating a countdown timer: using JavaScript and using only CSS. We started with a basic JavaScript countdown timer, adding functionality and styling to make it user-friendly and visually appealing. Then, we implemented a CSS-only countdown timer, showcasing the power of CSS for creating simple yet effective animations.

Whether you choose the CSS-only approach for its simplicity or the JavaScript approach for its flexibility, you now have the tools and knowledge to implement a countdown timer that suits your project\\'s needs.


Is your frontend hogging your users\\' CPU?

As web frontends get increasingly complex, resource-greedy features demand more and more from the browser. If you’re interested in monitoring and tracking client-side CPU usage, memory usage, and more for all of your users in production, try LogRocket.

\\\"How

LogRocket is like a DVR for web and mobile apps, recording everything that happens in your web app, mobile app, or website. Instead of guessing why problems happen, you can aggregate and report on key frontend performance metrics, replay user sessions along with application state, log network requests, and automatically surface all errors.

Modernize how you debug web and mobile apps — start monitoring for free.

","image":"http://www.luping.net/uploads/20241116/173173428967382b1172c95.gif","datePublished":"2024-11-16T13:35:44+08:00","dateModified":"2024-11-16T13:35:44+08:00","author":{"@type":"Person","name":"luping.net","url":"https://www.luping.net/articlelist/0_1.html"}}
”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 如何使用 CSS 构建倒计时器

如何使用 CSS 构建倒计时器

发布于2024-11-16
浏览:893

Written by Carlos Mucuho✏️

Countdown timers are a popular feature on many websites, enhancing functionality for events, sales, and user engagement. While JavaScript is commonly used for dynamic behavior on the web, it is also possible to create a functional and visually appealing countdown timer using only CSS.

In this tutorial, we will explore both approaches, starting with a basic JavaScript countdown timer and then moving on to a CSS-only countdown timer. At the end, we will compare the performance of both approaches using Chrome DevTools and discuss each of their pros and cons.

Creating a basic JavaScript countdown timer

We'll start by creating a simple countdown timer that updates every second. The timer will include a start and pause button to control its operation.

Creating the directory structure

Before we create the JavaScript countdown timer, we need to create a directory to store the applications we will build throughout this tutorial.

Open a terminal window, navigate to a directory suitable for your project, and use the following command to create a directory named countdown-timer:

mkdir countdown-timer

Then, navigate to this directory:

cd countdown-timer

Create two subdirectories named javascript-countdown and css-only-countdown, and inside each subdirectory, create a subdirectory named public:

mkdir javascript-countdown && mkdir javascript-countdown/public
mkdir css-only-countdown && mkdir css-only-countdown/public

Creating the application server

Next, navigate to the javascript-countdown subdirectory, initialize a new node project with default settings, and install the express package:

cd javascript-countdown
npm init -y
npm install express

Open your favorite text editor, create a file named server.js, and add the following code to it:

const express = require('express');
const app = express();
const port = 3001

app.use(express.static('public'));
app.listen(port, () => {
  console.log(`Javascript countdown app server started on port ${port}`);
});

The code above creates an express server that will be used to serve the JavaScript countdown application in port 3001.

HTML structure

Still in your text editor, create the following files in the public subdirectory located inside the javascript-countdown directory:

  • index.html for the HTML code
  • styles.css for the CSS code
  • index.js for the JavaScript code

Add the following code to index.html:



  Javascript Countdown Timer

This HTML file sets up a basic structure with a container holding control buttons and a countdown display area.

Implementing countdown logic using JavaScript

Next, we'll add JavaScript to manage the countdown logic. Add the following code to index.js:

window.addEventListener("load", () => {
  const startBtn = document.getElementById('startBtn');
  const pauseBtn = document.getElementById('pauseBtn');
  const countdownView = document.getElementsByClassName('countdown')[0];

  let totalTime = 10;
  let timeLeft;
  let countDownIntervalID;
  let isPaused = false;

  pauseBtn.style.display = 'none';
});  

In this block of code, we initialize the startBtn, pauseBtn, and countdownView elements by their respective IDs and classes. We also set some initial variables: totalTime, timeLeft, countDownIntervalID, and isPaused. Additionally, we set the pause button to hide initially.

Now, let's add event listeners for the start and pause buttons:

startBtn.addEventListener('click', startOrStopTimer);
pauseBtn.addEventListener('click', pauseOrResumeTimer);

These lines attach click event listeners to the start and pause buttons. The functions startOrStopTimer and pauseOrResumeTimer are defined later to handle the button clicks.

Add the following code to define the startOrStopTimer function:

function startOrStopTimer() {
  startBtn.innerHTML = startBtn.innerHTML === 'Start' ? 'Stop' : 'Start';
  if (countDownIntervalID === undefined && !isPaused) {
    timeLeft = totalTime;
    startTimer();
    pauseBtn.style.display = 'inline';
  } else {
    stopTimer();
    countdownView.innerHTML = '';
    pauseBtn.style.display = 'none';
    isPaused = false;
    pauseBtn.innerHTML = 'Pause';
  }
}

In this function, we toggle the start button text between Start and Stop. If the countdown is not running and not paused, we initialize timeLeft to totalTime and start the timer. Otherwise, we stop the timer and reset the view.

Now, define the startTimer function:

function startTimer() {
  countDownIntervalID = setInterval(() => {
    countdownView.innerHTML = timeLeft;

    if (timeLeft === 0) {
      stopTimer();
      startBtn.innerHTML = 'Start';
      pauseBtn.style.display = 'none';
      countdownView.innerHTML = '';
    } else {
      timeLeft = timeLeft - 1;
    }
  }, 1000);
}

This function sets an interval to update the countdown every second. If timeLeft reaches zero, we stop the timer, reset the start button text, and hide the pause button.

Next, add the stopTimer function:

function stopTimer() {
  if (countDownIntervalID !== undefined) {
    clearInterval(countDownIntervalID);
    countDownIntervalID = undefined;
  }
}

This function clears the countdown interval and resets countDownIntervalID. Finally, add the pauseOrResumeTimer function:

function pauseOrResumeTimer() {
  isPaused = !isPaused;
  pauseBtn.innerHTML = isPaused ? 'Resume' : 'Pause';

  if (countDownIntervalID !== undefined) {
    stopTimer();
  } else {
    startTimer();
  }
}

In this function, we toggle the pause state and button text between Pause and Resume. If the countdown is running, we stop the timer; otherwise, we start it again.

CSS styling

Now, let's style the countdown timer using CSS. Add the following code to styles.css:

body {
  background-color: black;
  font-family: Arial, sans-serif;
  height: 100%;
}

.container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.controls {
  width: 20%;
  margin-top: 10%;
  display: flex;
  justify-content: space-between;
  flex-direction: row;
  flex-wrap: wrap;
}

.countdown-container {
  position: relative;
  width: 20vw;
  height: 20vw;
  margin-top: 2%;
  border: 0.4em solid #9b51e0;
}

button {
  font-size: 1.5em;
  border: none;
  padding: 0.3em;
  background-color: #9b51e0;
  border-radius: 0.4em;
  color: white;
}

.countdown {
  position: relative;
  width: 100%;
  height: 100%;
  list-style: none;
  padding: 0;
  margin: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 5em;
  color: #9b51e0;
}

This CSS defines styles for the countdown timer interface. The body background is set to black, and we use Arial as the primary font. The .container class is styled to center its contents and provide spacing between elements. The .controls class styles the buttons for starting and pausing the timer, ensuring they are evenly spaced and responsive. The .countdown-container class defines the size and appearance of the countdown display, including a border and margin.

Go back to your terminal and run the following command to start serving the JavaScript countdown application:

node server.js

Open a new tab in your browser, navigate to http://localhost:3001, and you should see something similar to the following: How to build a countdown timer using CSS Test out the countdown timer and once you are done, terminate the server application and move to the next step.

Adding a circular progress indicator

To enhance the user experience of our countdown timer, let’s add a circular progress indicator to give the user a visual representation of the time remaining.

First, we need to modify our HTML code to include the circular progress element. In index.html, we add a span element with a class of circular-progress inside the countdown-container div. This span element will be used to create the circular progress indicator:

Next, we need to define the CSS for the circular progress indicator. In styles.css, we add the following code:

.countdown-container {
  ...
  /* border : 0.4em solid #9b51e0; */
}
.circular-progress {
  width: 20vw;
  height: 20vw;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  transition: 0.5s;
  background-color: #13171f;
}

.circular-progress::before {
  width: 18.5vw;
  height: 18.5vw;
  content: "";
  position: absolute;
  border-radius: 50%;
  background-color: black;
}

This code first removes the border from the countdown-container div, then sets the dimensions and shape of the circular progress indicator, as well as its position and background color. We also add a ::before pseudo-element to create the inner circle of the progress indicator.

Now we need to add the JavaScript code to animate the circular progress indicator.

Add the following code in the variables initialization block:

const circularProgressEl = document.getElementsByClassName("circular-progress")[0];
let circularProgress;
let circularProgressIntervalID;

This code initializes the circularProgressEl variable to target the circular progress element and creates two new variables, circularProgress and circularProgressIntervalID, that will be used to animate the progress indicator.

Add the following code below the pauseOrResumeTimer() function:

function startCircularProgressAnimation() {
  let start = totalTime - timeLeft;
  let degreesPerSecond = 360 / totalTime;
  let degreesPerInterval = degreesPerSecond / 20;
  circularProgress = degreesPerSecond * start; 

  circularProgressIntervalID = setInterval(() => {
    if (Math.round(circularProgress) === 360) {
      clearInterval(circularProgressIntervalID);
    } else {
      circularProgress = circularProgress   degreesPerInterval;
      circularProgressEl.style.background = `conic-gradient(#9b51e0 ${circularProgress}deg, #13171f 0deg)`;
    }
  }, 50);
}

This code defines the startCircularProgressAnimation function, which calculates the starting point and degree of rotation for the circular progress indicator, and sets up an interval to animate the progress indicator.

Add the following code below the startCircularProgressAnimation:

function resumeCircularProgressAnimation() {
  startCircularProgressAnimation();
}

function pauseCircularProgressAnimation() {
  clearInterval(circularProgressIntervalID);
}

function stopCircularProgressAnimation() {
  clearInterval(circularProgressIntervalID);
  circularProgressEl.style.background = `conic-gradient(#9b51e0 0deg, #13171f 0deg)`;
}

This code defines the resumeCircularProgressAnimation, pauseCircularProgressAnimation, and stopCircularProgressAnimation functions, which are used to start, pause, and stop the circular progress animation.

Finally, we need to modify the startOrStopTimer and pauseOrResumeTimer functions to start and stop the circular progress animation along with the timer:

function startOrStopTimer() {
  // ...
  if (countDownIntervalID === undefined && !isPaused) {
    // ...
    startCircularProgressAnimation();
  } else {
    // ...
    stopCircularProgressAnimation();
  }
}

function pauseOrResumeTimer() {
  // ...
  if (countDownIntervalID !== undefined) {
    stopTimer();
    pauseCircularProgressAnimation();
  } else {
    startTimer();
    resumeCircularProgressAnimation();
  }
}

With these modifications, our countdown timer now includes a circular progress indicator that animates along with the timer.

Return to your terminal and run the following command to start serving the JavaScript countdown application:

node server.js

Go back to the tab in your browser where you visited the http://localhost:3001 URL, refresh the page, and you should see something similar to the following: How to build a countdown timer using CSS

Implementing a CSS-only countdown timer

In this section, we'll dive into creating a countdown timer that updates every second and is made using only CSS. Our timer will be simple yet functional, featuring start and pause buttons to control its operation.

Creating the application server

Navigate to the css-only-countdown subdirectory, initialize a new node project, and install the express package:

cd ../css-only-countdown
npm init -y
npm install express

Then, return to your text editor, create a file named server.js, and add the following code to it:

const express = require('express');
const app = express();
const port = 3002
app.use(express.static('public'));

app.listen(port, () => {
  console.log(`Css-only countdown app server started on port ${port}`);
});

The code above creates an express server that will be used to serve the JavaScript countdown application in port 3002.

HTML structure

Still in your text editor, create the following files in the public subdirectory:

  • index.html for the HTML code
  • styles.css for the CSS code

Add the following code to the index.html file:



  CSS Countdown Timer
  • 10
  • 9
  • 8
  • 7
  • 6
  • 5
  • 4
  • 3
  • 2
  • 1

This code sets up the basic structure of our countdown timer. It includes a container div that holds the controls for starting and pausing the timer, as well as the countdown display itself. The controls div contains two checkboxes with labels that will serve as our start and pause buttons. These buttons toggle their respective states using CSS, thanks to the checkbox hack.

The countdown-container div holds an unordered list (ul) of list items (li) representing the countdown numbers from 10 to one. These numbers will be displayed one by one as the timer counts down.

CSS styling

Now, let's style the countdown timer using CSS. Add the following code to styles.css:

body {
  background-color: black;
  font-family: Arial, sans-serif;
  height: 100%;
}

.container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.controls {
  width: 20%;
  margin-top: 10%;
  display: flex;
  justify-content: space-between;
  flex-direction: row;
  flex-wrap: wrap;
}

.countdown-container {
  position: relative;
  width: 20vw;
  height: 20vw;
  margin-top: 12%;
  border : 0.4em solid #9b51e0;
}

#startLabel span {
  display: none;
}

label {
  cursor: pointer;
  font-size: 1.5em;
  padding: 0.3em;
  background-color: #9b51e0;
  border-radius: 0.4em;
  color: white;
}

#startBtn:checked~#startLabel span:nth-child(1) {
  display: inline;
}

#startBtn:not(:checked)~#startLabel span:nth-child(2) {
  display: inline;
}

#startBtn:not(:checked)~#pauseLabel,
#pauseBtn {
  display: none;
}

#pauseLabel span {
  display: none;
}

#pauseBtn:checked~#pauseLabel span:nth-child(1) {
  display: inline;
}

#pauseBtn:not(:checked)~#pauseLabel span:nth-child(2) {
  display: inline;
}

.checkbox-wrapper {
  display: none;
}

In this CSS file, we start by setting some basic styles for the body and container. The body has a black background and uses the Arial font. The container is centered using flexbox and has a margin to push it down from the top of the viewport.

The controls div is styled to be responsive and to ensure that the buttons are spaced out evenly. The countdown-container div is styled with a border, which will later be replaced by the circular progress indicator.

We use the checkbox hack to toggle the visibility of the labels for the start and pause buttons. Depending on whether the checkboxes are checked or not, different spans within the labels are displayed. This allows the labels to show different text (Start or Stop, Pause or Resume) based on the state of the checkboxes.

Now, add the following code to the bottom of the styles.css file:

.countdown {
  position: relative;
  width: 100%;
  height: 100%;
  list-style: none;
  padding: 0;
  margin: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 5em;
  color: #9b51e0;
}

.countdown li {
  position: absolute;
  opacity: 0;
  transition: opacity 1s linear;
}

#startBtn:checked~.countdown-container .countdown li:nth-child(1) {
  animation-delay: 0s;
}

#startBtn:checked~.countdown-container .countdown li:nth-child(2) {
  animation-delay: 1s;
}

#startBtn:checked~.countdown-container .countdown li:nth-child(3) {
  animation-delay: 2s;
}

#startBtn:checked~.countdown-container .countdown li:nth-child(4) {
  animation-delay: 3s;
}

#startBtn:checked~.countdown-container .countdown li:nth-child(5) {
  animation-delay: 4s;
}

#startBtn:checked~.countdown-container .countdown li:nth-child(6) {
  animation-delay: 5s;
}

#startBtn:checked~.countdown-container .countdown li:nth-child(7) {
  animation-delay: 6s;
}

#startBtn:checked~.countdown-container .countdown li:nth-child(8) {
  animation-delay: 7s;
}

#startBtn:checked~.countdown-container .countdown li:nth-child(9) {
  animation-delay: 8s;
}

#startBtn:checked~.countdown-container .countdown li:nth-child(10) {
  animation-delay: 9s;
}

@keyframes countdownAnimation {
  0%,
  10% {
    opacity: 1;
  }
  11%,
  100% {
    opacity: 0;
  }
}

#startBtn:checked~.countdown-container .countdown li {
  animation: countdownAnimation 10s steps(10) forwards;
}

#pauseBtn:checked~.countdown-container .countdown li {
  animation-play-state: paused;
}

With this code, we style the countdown list. The countdown class is positioned absolutely within the countdown-container, and its list items are initially hidden with opacity: 0.

We then use keyframes and the animation property to create the countdown effect. The list items are displayed one by one with a delay using the animation-delay property. The countdownAnimation keyframes control the visibility of each list item, making them visible for a short period before hiding them again.

We also pause the animation when the pause button is checked, using the animation-play-state property.

Go back to your terminal and run the following command to start serving the CSS-only countdown application:

node server.js

Open a new tab in your browser, navigate to http://localhost:3002 URL, and you should see something similar to the following: How to build a countdown timer using CSS Test out the countdown timer and once you are done, terminate the server application and move to the next step.

Adding a circular progress indicator

To make the countdown timer more visually appealing, we can add a circular progress indicator that shows the remaining time. To do this, we will modify the HTML and CSS code as follows:

First, replace the countdown-container div in the index.html file with the following code:

  • 10
  • 9
  • 8
  • 7
  • 6
  • 5
  • 4
  • 3
  • 2
  • 1

In this code, we add a span element with a class of circular-progress inside the countdown-container div.

Next, add the following code to the styles.css file:

.countdown-container {
  ...
  /* border : 0.4em solid #9b51e0; */
}

.circular-progress {
  width: 20vw;
  height: 20vw;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  transition: 0.5s;
  background: conic-gradient(#9b51e0 var(--angle), #13171f 0deg);
}

.circular-progress::before {
  width: 18.5vw;
  height: 18.5vw;
  content: "";
  position: absolute;
  border-radius: 50%;
  background-color: black;
}

@keyframes circularProgressAnimation {
  to {
    --angle: 360deg;
  }
}

@property --angle {
  syntax: "";
  initial-value: 0deg;
  inherits: false;
}

#startBtn:checked~.countdown-container .circular-progress {
  opacity: 1;
  animation: circularProgressAnimation 10s linear;
}

#pauseBtn:checked~.countdown-container .circular-progress {
  animation-play-state: paused;
}

In this code, we first remove the border from the countdown-container div, and then add styles for the circular-progress class. The circular progress indicator is a span element that is absolutely positioned within the countdown-container. It uses a conic gradient to create the circular progress effect.

We also define a keyframe animation, circularProgressAnimation, that animates the progress indicator from 0 to 360 degrees over the duration of the countdown. The --angle CSS property is used to control the angle of the gradient.

Finally, we use the checkbox hack to start and pause the circular progress animation along with the countdown numbers. The animation is applied to the circular-progress span when the start button is checked and paused when the pause button is checked.

With these modifications, our countdown timer now includes a circular progress indicator that animates along with the timer.

Go back to your terminal and run the following command to start serving the CSS-only countdown application:

node server.js

Return to the tab in your browser where you visited the http://localhost:3002 URL, refresh the page, and you should see something similar to the following: How to build a countdown timer using CSS

Using Chrome DevTools to compare timer performance

Now that we have implemented both the CSS-only and JavaScript countdown timers, let's compare their performance using Chrome DevTools.

To get started, open the Chrome browser and navigate to the webpage containing the countdown timers. Right-click anywhere on the page and select Inspect to open Chrome DevTools.

In the DevTools window, click on the Network tab and then refresh both the JavaScript and CSS-only countdown pages. This tab allows you to monitor all network requests made by the page, including HTML, CSS, JavaScript, and other resources: How to build a countdown timer using CSS

By analyzing the requests, you can determine how many resources are being loaded, their sizes, and the overall impact on page load time:

CSS-only countdown timer JavaScript countdown timer
Number of requests 2 3
Total size 4.5 KB 4.7 KB
Page load 24 ms 27 ms

From these results, we can see that the CSS-only countdown timer requires fewer requests and has a slightly smaller total size compared to the JavaScript countdown timer. This leads to a marginally faster page load time for the CSS-only version, making it more efficient in terms of initial loading.

Now, in the DevTools window, navigate to the Performance tab and initiate a recording session by clicking on the Record button. To evaluate the JavaScript countdown timer, click on the Start button located on its respective page and allow the timer to run its course. Once the timer has stopped, cease the recording in the Performance tab.

Do this process for both the JS and CSS-only countdown pages to gather performance data for each implementation. The Performance tab offers a comprehensive analysis of your page's runtime performance, encompassing scripting, rendering, and painting times. By analyzing these metrics, you can pinpoint areas that may require optimization to enhance the performance of your web application:

CSS-only countdown timer JavaScript countdown timer
Scripting 2 ms 49 ms
Rendering 510 ms 103 ms
Painting 275 ms 55 ms

Interpreting these results, we observe that the scripting time for the CSS-only countdown timer is significantly lower than for the JavaScript countdown timer, indicating minimal execution overhead. However, the CSS-only countdown timer has higher rendering and painting times. This is because CSS animations can sometimes require more effort from the browser to render, especially for complex styles or transitions.

In contrast, the JavaScript countdown timer shows higher scripting time due to the logic involved in updating the countdown, but it benefits from lower rendering and painting times. This suggests that while JavaScript adds some overhead in terms of script execution, it can be more efficient in terms of updating the DOM and rendering changes.

Overall, the CSS-only countdown timer is more efficient for scenarios where minimizing script execution time is critical, whereas the JavaScript timer may perform better in cases where rendering and painting times are the primary concern.

Pros and cons of each approach

Having explored both the CSS-only and JavaScript countdown timers, let's weigh their advantages and disadvantages to determine which approach best suits your needs.

CSS-only countdown timer

The CSS-only countdown timer leverages pure CSS to achieve the countdown effect, providing a lightweight and straightforward solution.

Its pros include the following:

  • Minimal scripting overhead: As seen in our performance analysis, the CSS-only timer requires very little scripting, resulting in lower CPU usage for script execution. This can be beneficial for enhancing overall page performance, especially on devices with limited processing power
  • Simplified codebase: By utilizing CSS for animations, the code remains cleaner and more maintainable. This approach reduces the complexity of the implementation and can make it easier for developers to understand and manage the code

Cons to this approach include:

  • Higher rendering and painting times: The CSS-only timer tends to have higher rendering and painting times. This is due to the nature of CSS animations, which can be more demanding on the browser’s rendering engine. This could impact performance on pages with multiple animations or complex layouts
  • Limited interactivity: CSS animations are inherently less flexible than JavaScript. Implementing more interactive features, such as dynamic updates or conditional logic, can be challenging and may require additional JavaScript, partially negating the simplicity advantage

JavaScript countdown timer

The JavaScript countdown timer, on the other hand, uses JavaScript to manage the countdown logic and DOM updates. This approach offers greater control and flexibility.

Pros of this approach include:

  • Enhanced control and flexibility: JavaScript provides fine-grained control over the countdown logic and DOM manipulation. This allows for more complex interactions, conditional behavior, and dynamic updates, making it suitable for more sophisticated applications
  • Efficient rendering and painting: As our performance analysis indicates, the JavaScript timer benefits from lower rendering and painting times. JavaScript can optimize updates to the DOM, resulting in smoother animations and better performance in scenarios involving frequent updates

Cons include:

  • Higher scripting overhead: The primary drawback of the JavaScript countdown timer is the increased scripting time. The JavaScript logic introduces additional CPU overhead, which can impact performance, particularly on devices with lower processing power or on pages with heavy script usage
  • Increased complexity: Implementing a JavaScript countdown timer involves writing and managing more code, which can increase the complexity of the project. This added complexity can make the codebase harder to maintain and debug

The CSS-only timer is lightweight and easy to understand, making it a good choice for simple countdowns with minimal scripting. However, it may struggle with more complex animations and interactive features. On the other hand, the JavaScript timer offers greater control and flexibility, allowing for more dynamic interactions. This comes at the cost of higher scripting overhead and increased complexity.

Ultimately, the choice between the two approaches depends on the specific needs of your project and the trade-offs you are willing to accept.

Conclusion

In this tutorial, we explored two methods for creating a countdown timer: using JavaScript and using only CSS. We started with a basic JavaScript countdown timer, adding functionality and styling to make it user-friendly and visually appealing. Then, we implemented a CSS-only countdown timer, showcasing the power of CSS for creating simple yet effective animations.

Whether you choose the CSS-only approach for its simplicity or the JavaScript approach for its flexibility, you now have the tools and knowledge to implement a countdown timer that suits your project's needs.


Is your frontend hogging your users' CPU?

As web frontends get increasingly complex, resource-greedy features demand more and more from the browser. If you’re interested in monitoring and tracking client-side CPU usage, memory usage, and more for all of your users in production, try LogRocket.

How to build a countdown timer using CSS

LogRocket is like a DVR for web and mobile apps, recording everything that happens in your web app, mobile app, or website. Instead of guessing why problems happen, you can aggregate and report on key frontend performance metrics, replay user sessions along with application state, log network requests, and automatically surface all errors.

Modernize how you debug web and mobile apps — start monitoring for free.

版本声明 本文转载于:https://dev.to/logrocket/how-to-build-a-countdown-timer-using-css-27ik?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 除了“if”语句之外:还有哪些地方可以在不进行强制转换的情况下使用具有显式“bool”转换的类型?
    除了“if”语句之外:还有哪些地方可以在不进行强制转换的情况下使用具有显式“bool”转换的类型?
    无需强制转换即可上下文转换为 bool您的类定义了对 bool 的显式转换,使您能够在条件语句中直接使用其实例“t”。然而,这种显式转换提出了一个问题:“t”在哪里可以在不进行强制转换的情况下用作 bool?上下文转换场景C 标准指定了四种值可以根据上下文转换为的主要场景bool:语句:if、whi...
    编程 发布于2024-11-16
  • Bootstrap 4 Beta 中的列偏移发生了什么?
    Bootstrap 4 Beta 中的列偏移发生了什么?
    Bootstrap 4 Beta:列偏移的删除和恢复Bootstrap 4 在其 Beta 1 版本中引入了重大更改柱子偏移了。然而,随着 Beta 2 的后续发布,这些变化已经逆转。从 offset-md-* 到 ml-auto在 Bootstrap 4 Beta 1 中, offset-md-*...
    编程 发布于2024-11-16
  • 在 Go 中使用 WebSocket 进行实时通信
    在 Go 中使用 WebSocket 进行实时通信
    构建需要实时更新的应用程序(例如聊天应用程序、实时通知或协作工具)需要一种比传统 HTTP 更快、更具交互性的通信方法。这就是 WebSockets 发挥作用的地方!今天,我们将探讨如何在 Go 中使用 WebSocket,以便您可以向应用程序添加实时功能。 在这篇文章中,我们将介绍: WebSoc...
    编程 发布于2024-11-16
  • 如何在 SQL 中计算某个值的总和,同时确保每行只计算一次?
    如何在 SQL 中计算某个值的总和,同时确保每行只计算一次?
    在 SQL 中使用 SUM() 对不同值进行分组在 MySQL 查询中,您想要计算以下值的总和转换表,同时确保每行仅计算一次。为了实现这一点,您需要将 DISTINCT 关键字与 SUM() 函数结合使用。但是,您遇到了重复行导致 SUM() 结果膨胀的问题。要解决此问题,请考虑表中的主键关系。如果...
    编程 发布于2024-11-16
  • 如何使用 MySQL 查找今天生日的用户?
    如何使用 MySQL 查找今天生日的用户?
    如何使用 MySQL 识别今天生日的用户使用 MySQL 确定今天是否是用户的生日涉及查找生日匹配的所有行今天的日期。这可以通过一个简单的 MySQL 查询来实现,该查询将存储为 UNIX 时间戳的生日与今天的日期进行比较。以下 SQL 查询将获取今天有生日的所有用户: FROM USERS ...
    编程 发布于2024-11-16
  • Vite中环境变量的处理
    Vite中环境变量的处理
    在现代 Web 开发中,管理敏感数据(例如 API 密钥、数据库凭据以及不同环境的各种配置)至关重要。将这些变量直接存储在代码中可能会带来安全风险并使部署复杂化。 Vite,一个现代的前端构建工具,提供了一种通过.env文件管理环境变量的简单方法。 什么是 .env 文件? .env 文件是一个简单...
    编程 发布于2024-11-16
  • 如何使用 Django REST Framework 高效处理嵌套序列化器中的外键分配?
    如何使用 Django REST Framework 高效处理嵌套序列化器中的外键分配?
    Django REST Framework 中的嵌套序列化器的外键分配Django REST Framework (DRF) 提供了一种管理外键关系的便捷方法序列化数据。然而,在嵌套序列化器中获得所需的行为可能具有挑战性。嵌套序列化器中的外键分配嵌套序列化器继承其父序列化器的行为。默认情况下,它们不...
    编程 发布于2024-11-16
  • 如何从 CodeIgniter URL 中删除“index.php”?
    如何从 CodeIgniter URL 中删除“index.php”?
    CodeIgniter .htaccess 和 URL 重写问题导航 CodeIgniter 应用程序通常需要从 URL 中删除“index.php”,以允许用户访问具有更清晰语法的页面。不过,新用户在这个过程中可能会遇到困难。删除“index.php”的关键在于修改应用程序配置文件(applica...
    编程 发布于2024-11-16
  • 您可以在 `` 标签内嵌套更多的 `` 元素吗?
    您可以在 `` 标签内嵌套更多的 `` 元素吗?
    不常见的 HTML 结构: 可以容纳 以外的标签吗?在 HTML 世界中,嵌套标签可以创建复杂的结构。然而,某些标签的放置有时会受到限制。以神秘的 标签为例,许多人认为它只能嵌套 元素。深入研究:您的询问源于探索标签是否有效的愿望除了 之外的其他人都可以在 中找到一个家。为了揭开这个概念的...
    编程 发布于2024-11-16
  • 如何使用 XPath 条件选择 XML 文档中的特定节点?
    如何使用 XPath 条件选择 XML 文档中的特定节点?
    利用 XPath 条件选择节点通过 XPath 导航 XML 文档时,通常需要根据特定条件限制检索的节点。在此示例中,我们的任务是根据日期属性有选择地检索节点。以下 XPath 表达式从提供的 XML 文档中检索所有 节点:$nodes = $xml->xpath('//xml/events...
    编程 发布于2024-11-16
  • 为什么“margin: auto”不能与绝对定位的元素一起使用?
    为什么“margin: auto”不能与绝对定位的元素一起使用?
    了解绝对定位边距自动问题当将“position:absolute”应用于具有“margin-left:auto”和“的元素时margin-right: auto”,您可能会注意到边距似乎没有效果。此行为不同于“位置:相对”,其中边距按预期工作。为了理解这种差异,让我们更深入地研究底层机制。当一个元素...
    编程 发布于2024-11-16
  • Go 如何处理方法中的指针和值接收者?
    Go 如何处理方法中的指针和值接收者?
    Go 指针:接收者和值类型在 Go 中,指针对于理解面向对象编程和内存管理是必不可少的。在处理指针时,掌握方法中接收器类型之间的区别至关重要。您提供的 Go Tour 示例说明了这个概念:type Vertex struct { X, Y float64 } func (v *Vertex)...
    编程 发布于2024-11-16
  • 如何从 Python 中的字符串列表创建多个变量?
    如何从 Python 中的字符串列表创建多个变量?
    如何从字符串列表创建多个变量? [重复]许多编程场景要求我们同时操作多个对象或变量。一个常见的挑战是从字符串列表创建多个变量,其中每个变量的名称与列表中的相应元素匹配。在 Python 中,您可以使用字典理解来完成此操作:names = ['apple', 'orange', 'banana'] f...
    编程 发布于2024-11-16
  • 如何在 PHP 中组合两个关联数组,同时保留唯一 ID 并处理重复名称?
    如何在 PHP 中组合两个关联数组,同时保留唯一 ID 并处理重复名称?
    在 PHP 中组合关联数组在 PHP 中,将两个关联数组组合成一个数组是一项常见任务。考虑以下请求:问题描述:提供的代码定义了两个关联数组,$array1和$array2。目标是创建一个新数组 $array3,它合并两个数组中的所有键值对。 此外,提供的数组具有唯一的 ID,而名称可能重合。要求是构...
    编程 发布于2024-11-16
  • 外键可以引用多态关联中的多个表吗?
    外键可以引用多态关联中的多个表吗?
    多态外键:一个外键可以引用多个表吗?关系数据库中外键的概念通常涉及指定确切的目标参考列应指向的表。然而,在处理多态关联时,其中一个表与一组中的多个其他表有关系,就会出现问题:是否可以有一个可以引用这些表中任何一个表的外键?答案:否在MySQL和PostgreSQL中,外键约束只能引用单个父表。此约束...
    编程 发布于2024-11-16

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3