2017-10-18 59 views
-1

我想知道如何在點擊時更改數據屬性。我想要做的是增加25的值。所以我有一個進度條和一個按鈕。眼下進度條具有25的值。當我點擊按鈕,我想它遞增到50,75,100點擊更改數據屬性

下面是代碼:

let button = document.getElementById("btn"); 
 
let bar = document.getElementById("progress-bar"); 
 

 
button.addEventListener('click', function(){ 
 
    console.log("you clicked the btn"); 
 
});
body { 
 
    max-width: 1200px; 
 
    margin: 0 auto; 
 
    padding: 10px; 
 
    display: -webkit-box; 
 
    display: -ms-flexbox; 
 
    display: flex; 
 
    -ms-flex-wrap: wrap; 
 
     flex-wrap: wrap; 
 
    margin-top: 3em; 
 
} 
 

 
progress { 
 
    -webkit-appearance: none; 
 
    -moz-appearance: none; 
 
      appearance: none; 
 
    width: 100%; 
 
    height: 20px; 
 
} 
 

 
progress::-webkit-progress-bar { 
 
    background-color: #ccc; 
 
    width: 100%; 
 
} 
 

 
progress::-webkit-progress-value { 
 
    background-color: orange !important; 
 
} 
 

 
button { 
 
    margin-top: 2em; 
 
    background: black; 
 
    color: white; 
 
    border: none; 
 
    padding: .5em 2em; 
 
} 
 
button:hover { 
 
    background: #1a1a1a; 
 
}
<body> 
 
    <h2>Quiz Progress</h2> 
 
    <progress max='100' value='25'></progress> 
 
    <button id='btn'>Next</button> 
 
</body>

回答

1

你可以使用**value**屬性progress元素。您沒有將id分配給進度元素,但您正在嘗試訪問它。

let button = document.getElementById("btn"); 
 
let bar = document.getElementById("progress-bar"); 
 

 
button.addEventListener('click', function(){ 
 
    //console.log("you clicked the btn"); 
 
    if(bar.value>=100) 
 
    { 
 
    bar.value=100; 
 
    } 
 
    else 
 
    { 
 
    bar.value+=25; 
 
    } 
 
    
 
});
body { 
 
    max-width: 1200px; 
 
    margin: 0 auto; 
 
    padding: 10px; 
 
    display: -webkit-box; 
 
    display: -ms-flexbox; 
 
    display: flex; 
 
    -ms-flex-wrap: wrap; 
 
     flex-wrap: wrap; 
 
    margin-top: 3em; 
 
} 
 

 
progress { 
 
    -webkit-appearance: none; 
 
    -moz-appearance: none; 
 
      appearance: none; 
 
    width: 100%; 
 
    height: 20px; 
 
} 
 

 
progress::-webkit-progress-bar { 
 
    background-color: #ccc; 
 
    width: 100%; 
 
} 
 

 
progress::-webkit-progress-value { 
 
    background-color: orange !important; 
 
} 
 

 
button { 
 
    margin-top: 2em; 
 
    background: black; 
 
    color: white; 
 
    border: none; 
 
    padding: .5em 2em; 
 
} 
 
button:hover { 
 
    background: #1a1a1a; 
 
}
<body> 
 
    <h2>Quiz Progress</h2> 
 
    <progress id="progress-bar" max='100' value='25'></progress> 
 
    <button id='btn'>Next</button> 
 
</body>

+0

非常感謝你對你的反應,這個幫了我很多! – ThomasBrushel