เรียนรู้วิธีการสร้างแถบความคืบหน้าการใช้ JavaScript
สร้างแถบความคืบหน้า
ขั้นตอนที่ 1) เพิ่ม HTML:
ตัวอย่าง
<div id="myProgress">
<div id="myBar"></div>
</div>
ขั้นตอนที่ 2) เพิ่ม CSS:
ที่จะทำให้การเคลื่อนไหวเป็นไปได้องค์ประกอบภาพเคลื่อนไหวจะต้องมีการเคลื่อนไหวเมื่อเทียบกับของ "parent container"
ตัวอย่าง
#myProgress {
position: relative;
width: 100%;
height:
30px;
background-color:
grey;
}
#myBar {
position: absolute;
width: 1%;
height:
100%;
background-color: green;
}
ลองตัวเอง» ขั้นตอนที่ 3) เพิ่ม JavaScript:
สร้างภาพเคลื่อนไหวโดยใช้ JavaScript:
ตัวอย่าง
function move() {
var elem = document.getElementById("myBar");
var width = 1;
var id =
setInterval(frame, 10);
function frame() {
if (width >= 100) {
clearInterval(id);
} else {
width++;
elem.style.width = width + '%';
}
}
}
ลองตัวเอง» เพิ่มป้ายกำกับ
หากคุณต้องการที่จะเพิ่มป้ายชื่อเพื่อแสดงให้เห็นว่าไกลผู้ใช้อยู่ในขั้นตอนการเพิ่มองค์ประกอบใหม่ภายใน (or outside) แถบความคืบหน้า:
ขั้นตอนที่ 1) เพิ่ม HTML:
ตัวอย่าง
<div id="myProgress">
<div id="myBar">
<div
id="label">10%</div>
</div>
</div>
ขั้นตอนที่ 2) เพิ่ม CSS:
ตัวอย่าง
/* If you want the label inside the progress bar */
#label {
text-align: center; /* If you want to center
it */
line-height: 30px; /* Set the line-height to the
same as the height of the progress bar container, to center it vertically */
color:
white;
}
ลองตัวเอง» ขั้นตอนที่ 3) เพิ่ม JavaScript:
หากคุณต้องการที่จะปรับปรุงแบบไดนามิกข้อความภายในฉลากเพื่อค่าเดียวกันของความกว้างของแถบความคืบหน้าให้เพิ่มความต่อไปนี้:
ตัวอย่าง
function move() {
var elem = document.getElementById("myBar");
var width = 10;
var id =
setInterval(frame, 10);
function frame() {
if (width >= 100) {
clearInterval(id);
} else {
width++;
elem.style.width = width + '%';
document.getElementById("label").innerHTML = width * 1 +
'%';
}
}
}
ลองตัวเอง»