【发布时间】:2020-12-06 03:29:36
【问题描述】:
我是 Javascript 新手,我已经通过一些教程和项目来熟悉该语言。我发现“dcode”在此链接上提供了一个进度条教程:https://www.youtube.com/watch?v=QxQRtwAtqKE 我一直在关注它,但我的 java 脚本代码似乎有一个错误,而讲师没有。
似乎在Javascript部分的update函数的style方法中。 我尝试重新排列更新函数的位置(将其放在 setValue() 上方),认为可能无法读取它的放置位置。但这似乎不起作用。我完全按照本教程进行操作,所以我不确定我是怎么弄错的。我有什么遗漏吗?
以下是我进行了一些修改的代码: Javascript代码:
// JavaScript source code
//creating a class for the progess bar (HP bar)
class ProgressBar {
contructor(element, initialValue = 0) {
this.valueElem = element.querySelector('.HP-value');
this.fillElem = element.querySelector('.HP-bar-fill');
this.setValue(initialValue);
//console.log(this.valueElem);
//console.log(this.fillElem);
}
setValue(newValue) {
if (newValue < 0) {
newValue = 0;
}
if (newValue > 100) {
newValue = 100;
}
this.value = newValue;
this.update();
}
update() {
const percentage = this.value + '%'; // 50%
this.fillElem.style.width = percentage; //Error displays for me here but not the instructor.
this.valueElem.textContent = percentage;
}
}
const pb1 = new ProgressBar(document.querySelector('.HP'), 80);
//calls the value from user to display the new percentage.
//In this case it should go from 50% to 80%.
body
{
}
.HP {
position: relative;
width: 300px;
height: 40px;
border: 2px solid black;
}
.HP-bar-fill {
height: 100%;
background: #36ed1a;
transition: width 0.5s;
}
.HP-value {
position: absolute; /*float above the nearest parent positioned element*/
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
font-weight: bold;
}
<!DOCTYPE html>
<!--Create your own progress bar in HTML, CSS, and Javascript | Web development tutorial-->
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="css/style.css">
<title>HealthBar</title>
</head>
<body>
<h1>Your HP</h1>
<div class="HP">
<div class="HP-value">50%</div>
<div class="HP-bar-fill"></div>
</div>
<script src="js/script.js"></script>
</body>
</html>
【问题讨论】:
-
错误说明了什么?在该行之前尝试
console.log(percentage); -
错误是:script.js:31 Uncaught TypeError: Cannot read property 'style' of undefined at ProgressBar.update (script.js:31) at ProgressBar.setValue (script.js:25)在 :1:5
标签: javascript html css progress-bar typeerror