【发布时间】:2019-03-06 16:38:20
【问题描述】:
我正在尝试以 OO 方式重新编写此演示: https://www.w3schools.com/howto/howto_js_progressbar.asp 这是我的代码:
document.getElementById("barButton").addEventListener("click", callMove);
function callMove(){
var bar1 = new ProgressBar();
bar1.move();
}
function ProgressBar() {
this.elem = document.getElementById("myBar"),
this.width = 1;
}
ProgressBar.prototype = {
constructor: ProgressBar,
move: function() {
this.id = setInterval(this.frame, 300);
},
frame: function() {
if(this.width >= 100) {
clearInterval(this.id);
}
else {
this.width++;
if(this.width >= 50) {
return;
}
this.elem.style.width = this.width + '%';
}
},
}
#myProgress {
width: 100%;
background-color: grey;
}
#myBar {
width: 1%;
height: 30px;
background-color: black;
}
<html>
<head>
<title>
This is a OO progress bar test.
</title>
<link rel="stylesheet" href="testOOProgressBar.css">
</head>
<body>
<div id="myProgress">
<div id="myBar"></div>
</div>
<br>
<button id="barButton">Click Me</button>
<script src="testOOProgressBar.js"></script>
</body>
</html>
问题是,一旦我单击按钮,该栏不会按预期进行,而是在控制台中有Uncaught TypeError: Cannot read property 'style' of undefined at frame。这里有什么问题?似乎this.width 没有从Progressbar() 传递到它的原型。
【问题讨论】:
-
this的上下文将随 setInterval 改变
标签: javascript html css oop