2017-10-18 71 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