我在php中的项目
我想创建一个倒数计时器,用于在有限的时间范围内询问问题,例如LMS 这里我使用了javascript倒计时器,但是当刷新页面时,javascript计时器被重置。
答案 0 :(得分:3)
您可以将开始时间存储在php会话中。然后,每次加载页面时,您都可以使用javascript继续倒数计时器,例如
<?php
//on every page
session_start();
//when you start
$_SESSION['start_time'] = time();
然后在每一页上:
<script type="text/javascript">
var startTime = <?php echo $_SESSION['start_time']; ?>;
//calculate remaining time
</script>
您需要注意时区不同或客户端时钟错误的时间。也许您可以用秒计算剩余时间并在每个页面上将其打印到javascript中,但之后您可能会在高延迟连接等情况下进行查看。
答案 1 :(得分:1)
尝试类似:
<?php
session_start();
//to reset the saved countdown
if (!empty($_REQUEST['resetCountdown']))
{
unset($_SESSION['startTime']);
}
if (empty($_SESSION['startTime']))
{
$_SESSION['startTime'] = time();
}
//In seconds
$startTime = time() - $_SESSION['startTime'];
?>
<script type="text/javascript">
var countdown = 60; //in seconds
var startTime = <?php echo $startTime; ?>;
startCountdown(startTime, countdown);
function startCountdown(startFrom, duration)
{
//countdown implementation
}
</script>
答案 2 :(得分:0)
您还可以将计时器存储在PHP中的会话变量中,以便在刷新页面时仍然保留时间。
答案 3 :(得分:0)
试试这个
<script>
// Set the date we're counting down to
var countDownDate = new Date("Aug 1, 2017 12:00:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>
并将其置于正文标记下。
<p id="demo"></p>