我已经在制作这段代码上工作了一段时间,但我似乎无法让它像我想要的那样工作。我想要一个提示,询问你在一个主题上工作了多长时间,然后在进度条上给出正确的宽度。
编辑:widthGenerator会创建弹出窗口,但我似乎无法将widthGenerator()中的变量宽度转换为Move()作为Move的宽度。
这是我的代码:
<body class="w3-container">
<div class="w3-progress-container w3-round-xlarge">
<div id="myBar" class="w3-progressbar w3-round-xlarge" style="width:1%"></div>
</div>
<button class="w3-btn" onclick="move()">Click Me</button>
<script>
function widthGenerator() {
var question = prompt("Enter number of hours worked:", "Enter here");
if (isNaN(question) == false) {
var width = (question * 2.33463);
break;
} else if (isNaN(question) == true) {
question = prompt("That is not a number; Enter the number of hours worked:", "Enter here");
break;
};
}
function move() {
var elem = document.getElementById("myBar");
var id = setInterval(frame, 1);
var width = widthGenerator()
function frame() {
if (width >= widthGenerator()) {
clearInterval(id);
} else {
width += 0.1;
elem.style.width = width + '%';
}
}
}
</script>
答案 0 :(得分:0)
您需要在widthGenerator()函数中使用return
语句:
function widthGenerator() {
var question = prompt("Enter number of hours worked:", "Enter here");
if (!isNaN(Number(question))) {
var width = (question * 2.33463);
} else {
question = prompt("That is not a number; Enter the number of hours worked:", "Enter here");
}
return width;
}
我不想修改你的代码,但请注意,用户可能永远不会根据widthGenerator()的编写方式输入数字。
答案 1 :(得分:0)
此代码确保用户被要求提供有效号码,直到他给出。它也有点清洁。如果你不在交换机内,我删除了它,因为它不是一个有效的语法。
您可能希望删除代码中的超时,因为无论如何都会在请求宽度后进行处理。从内部清除imeout胜利无所作为。最后,我删除了功能框架,理由1是为每次调用move()
创建的,但其次,大多数情况下,由于您可以使用匿名函数进行此类工作,因此它是不可能的。
function widthGenerator() {
var question = prompt("Enter number of hours worked:", "Enter here")
while(isNaN(question)){
question = prompt("That is not a number; Enter the number of hours worked:", "Enter here")
// this will make it loop, till the user gives a valid number
}
return (question * 2.33463)
}
function move() {
var elem = document.getElementById("myBar")
var width = widthGenerator()
// You don't really need the timeout, since you can make the if anyway.
var id = setInterval(function(){
// this is anonymous function, it is used if you need to pass a callback to
if (width >= widthGenerator()) {
// Clearing this timeout won't do anything as you allready did cleared it by calling it
clearInterval(id)
} else {
width += 0.1
elem.style.width = width + '%'
}
}, 1)
}
随时提出任何问题。