执行代码时隐藏和取消隐藏 <div> 或 <form>(进度条 a.o.)

问题描述 投票:0回答:1

目标是隐藏表单,执行一些操作并再次取消隐藏表单。例如,使用这个进度条代码我想执行以下操作,但隐藏/取消隐藏不起作用。我可能正在监督一些显而易见的事情。

    <!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Progress Bar Demo</title>
<script>
var button;
var count;
var countmax;
var progressbar;
var timerID;

function start(max) {
    show_div();
    button = document.getElementById("button");
    count = 0;
    countmax = max;
    progressbar = document.getElementById("bar");
    progressbar.max = countmax;

    timerID = setInterval(function(){update()},10);
    show_div();
}//end function

function update() {
    button.innerHTML = "Counting to " + countmax;
    count = count + 100;
    progressbar.value = count;
    if (count >= countmax) {
        clearInterval(timerID);
        button.innerHTML = "Ready";
        progressbar.value = 0;
    }//end if
}//end function

function show_div() {
  var x = document.getElementById("do_you_see_me?");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}//end function
</script>
</head>

<body>
    <div id="do_you_see_me?" style="display: block";>Hi there!</div>
<p>
    <button onclick="start(4321)" id="button" style="font-size:18px;">Ready</button><br>
    <br>
    <progress id="bar" value="0"></progress>
</p>
</body>
</html>
javascript progress-bar
1个回答
2
投票

您可以隐藏和取消隐藏它。您的代码的问题是,当您触发就绪按钮时,它会隐藏,然后自动取消隐藏代码。这是因为 setInterval() 函数是异步函数。那么你需要在 setInterval() 中调用 show_div() 函数。

    <!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Progress Bar Demo</title>
<script>
var button;
var count;
var countmax;
var progressbar;
var timerID;

function start(max) {
    hide_div();
    button = document.getElementById("button");
    count = 0;
    countmax = max;
    progressbar = document.getElementById("bar");
    progressbar.max = countmax;
    
    timerID = setInterval(function()
    {
        update()
        if(count>=countmax)
        {
            show_div();
        }
    },10);
}//end function

function update() {
    button.innerHTML = "Counting to " + countmax;
    count = count + 100;
    progressbar.value = count;
    if (count >= countmax) {
        clearInterval(timerID);
        button.innerHTML = "Ready";
        progressbar.value = 0;
    }//end if
}//end function

function show_div() {
  document.getElementById("do_you_see_me?").style.display="block";
}//end function

function hide_div()
{
     document.getElementById("do_you_see_me?").style.display="none";
}
</script>
</head>

<body>
    <div id="do_you_see_me?" style="display: block";>Hi there!</div>
<p>
    <button onclick="start(4321)" id="button" style="font-size:18px;">Ready</button><br>
    <br>
    <progress id="bar" value="0"></progress>
</p>
</body>
</html>

我希望这能解决您的问题。

© www.soinside.com 2019 - 2024. All rights reserved.