点击

时间:2017-10-18 20:58:51

标签: javascript html css dom

我想知道如何在点击时更改数据属性。我想要做的是将值增加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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

您可以使用progress元素的**value**属性。你没有将id分配给progress元素,但你试图访问它。

&#13;
&#13;
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;
  }
  
});
&#13;
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;
}
&#13;
<body>
  <h2>Quiz Progress</h2>
  <progress id="progress-bar" max='100' value='25'></progress>
  <button id='btn'>Next</button>
</body>
&#13;
&#13;
&#13;