บทความนี้อธิบายถึงวิธีการใช้แถบความคืบหน้าโดย JS แบ่งปันสำหรับการอ้างอิงของคุณ วิธีการใช้งานเฉพาะมีดังนี้:
1.settimeout และ Cleartimeout
<html> <head> <title> แถบความคืบหน้า </title> <style type = "text/css"> .container {width: 450px; ชายแดน: 1px Solid #6C9C2C; ความสูง: 25px; } #bar {พื้นหลัง: #95CA0D; ลอย: ซ้าย; ความสูง: 100%; TEXT-ALIGN: CENTER; ความสูงของสาย: 150%; } </style> <script type = "text/javascript"> function run () {var bar = document.getElementById ("bar"); var total = document.getElementById ("รวม"); bar.style.width = parseint (bar.style.width) + 1 + "%"; total.innerhtml = bar.style.width; if (bar.style.width == "100%") {window.cleartimeout (หมดเวลา); กลับ; } var timeout = window.settimeout ("run ()", 100); } window.onload = function () {run (); } </script> </head> <body> <div> <div id = "bar"> </div> </div> <span id = "total"> </span> </body> </html>ภาพการทำซ้ำ:
2.SetInterval และ ClearInterval
<html> <head> <title> แถบความคืบหน้า </title> <style type = "text/css"> .processContainer {width: 450px; ชายแดน: 1px Solid #6C9C2C; ความสูง: 25px; } #ProcessBar {พื้นหลัง: #95CA0D; ลอย: ซ้าย; ความสูง: 100%; TEXT-ALIGN: CENTER; ความสูงของสาย: 150%; } </style> <script type = "text/javascript"> function setProcess () {var processBar = document.getElementById ("processBar"); processBar.style.width = parseInt (processbar.style.width) + 1 + "%"; ProcessBar.innerHtml = processBar.style.width; if (processbar.style.width == "100%") {window.clearinterval (bartimer); }} var bartimer = window.setInterval (ฟังก์ชัน () {setProcess ();}, 100); window.onload = function () {bartimer; } </script> </head> <body> <div> <div id = "processbar"> </div> </div> </body> </html>ภาพการทำซ้ำ:
3. ความแตกต่างระหว่าง settimeout และ setInterval
settimeout () เรียกใช้งานรหัสเพียงครั้งเดียว หากคุณต้องการเรียกหลายครั้งให้ใช้ setInterval () เมธอด setInterval () จะเรียกใช้ฟังก์ชันต่อไปจนกว่าจะเรียกใช้ clearInterval () หรือปิดหน้าต่างหรือปล่อยให้รหัสเรียกว่า settimeout () อีกครั้ง
ฉันหวังว่าบทความนี้จะเป็นประโยชน์กับการเขียนโปรแกรม JavaScript ของทุกคน