Javascript 倒数计时器建立在 PHP 和 jQuery 上?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7115620/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Countdown timer built on PHP and jQuery?
提问by Avicinnian
After spending the last 45 minutes looking around for a solution, I can't seem to find an easy solution to creating a countdown timer using PHP and jQuery. Most already built scripts I've found are based purely on jQuery which require a ton of code, and more parameters then they should, plus, adaptability is pretty hard.
在花了最后 45 分钟四处寻找解决方案后,我似乎找不到使用 PHP 和 jQuery 创建倒数计时器的简单解决方案。我发现的大多数已经构建的脚本完全基于 jQuery,这需要大量代码和更多的参数,另外,适应性非常困难。
Here's my situation;
这是我的情况;
PHP:
PHP:
$countdown = date("h:i:s"); // This isn't my actual $countdown variable, just a placeholder
$countdown = date("h:i:s"); // This isn't my actual $countdown variable, just a placeholder
jQuery:
jQuery:
$(document).ready(function name() {
$("#this").load( function() {
setTimeout("name()", 1000)
}
}
});
HTML:
HTML:
<div id="this"><?php echo($countdown); ?></div>
<div id="this"><?php echo($countdown); ?></div>
My idea is that, every second, #this
is reloaded, giving a new value to it's contents, and as $countdown isn't a static variable, a new value will be loaded each time. This removes the need to deal with sessions (as a basic javascript countdown timer would reset on pageload, etc).
我的想法是,每秒钟#this
都会重新加载,为其内容赋予一个新值,并且由于 $countdown 不是静态变量,因此每次都会加载一个新值。这消除了处理会话的需要(因为基本的 javascript 倒数计时器将在页面加载等时重置)。
I would've though this would have worked, until I realized that the event binder .load()
doesn't reload #this
(I know silly me), so I guess what I'm wondering is - is there an event binder I can use to make this work or is there a way to get the functionality I'm looking for, without using a jQuery plugin (which doesn't match exactly what I want anyway)?
我会虽然这会奏效,直到我意识到事件绑定.load()
器不会重新加载#this
(我知道我很傻),所以我想我想知道的是 - 是否有一个事件绑定器可以用来完成这项工作或者有没有办法在不使用jQuery插件的情况下获得我正在寻找的功能(无论如何它与我想要的不完全匹配)?
回答by Joseph Silber
You should use Keith Wood's countdown timer: http://keith-wood.name/countdown.html
您应该使用 Keith Wood 的倒数计时器:http: //keith-wood.name/countdown.html
It is extremelyeasy to use.
它非常易于使用。
All you have to do is
你所要做的就是
$('#timer').countdown({
until: '<?php echo date("h:i:s"); ?>' // change this, obviously
});
Here's the fiddle: http://jsfiddle.net/tqyj4/289/
这是小提琴:http: //jsfiddle.net/tqyj4/289/
回答by cwallenpoole
OK, I know that an id is not a variable, but don't use this
as an ID. It is makes people cringe.
好的,我知道 id 不是变量,但不要this
用作 ID。真是让人不寒而栗。
To the rest, don't reload the value, set a value in JS in PHP and then count down.
剩下的,不要重新加载值,在PHP中的JS中设置一个值然后倒计时。
// place this in the <head> above the code below
echo "var t = " . time() . ";";
echo "var ft = " . /* your final time here */ . ";";
Then:
然后:
// this is a helper function.
function lpad( input, len, padstr )
{
if( !padstr ) padstr = " "; // this is the normal default for pad.
var ret = String( input );
var dlen = ret.length - len;
if( dlen > 0 ) return ret;
for( var i = 0; i < dlen; i++ ) ret = padstr + ret;
return ret;
}
$(document).ready(function name() {
$("#timer").load( function() { // I changed the id
$timer = $("timer"); // might as well cache it.
// interval, not timeout. interval repeats
var intval = setInterval(function(){
t += 500; // decrease the difference in time
if( t >= ft )
{
t = ft; // prevent negative time.
clearInterval( intval ) // cleanup when done.
}
var dt = new Date(ft - t);
$timer.innerHTML = dt.getHours() + ":" +
// pad to make sure it is always 2 digits
lpad( dt.getMinutes(), 2, '0' ) + ":" +
lpad( dt.getSeconds(), 2, '0' );
}, 500) // increments of .5 seconds are more accurate
}
}
});
回答by Matt R. Wilson
Once php has loaded a particular amount of time for the user, can you explain why this wouldn't be sufficient for your needs:
一旦 php 为用户加载了特定的时间,您能否解释为什么这不足以满足您的需求:
$(function(){
$timerdiv = $("#this");
timer();
});
function timer()
{
$timerdiv.html((int)$timerdiv.html() - 1);
setTimeout(timer, 1000);
}
回答by streetlogics
You are very close in your original code. Here's a modification to your code below that works as described, or at least so I think - I know it works, but am not sure if it meets your requirements, they were a little unclear. Obviously if you reload the page, you would have to rely on the PHP output to be different in order for the counter to not reset. Just to note though, I'm not entirely sure why you would use the .load function - that function is really just a wrapper for an AJAX call to grab the contents of another page and insert it into the selected div. I believe what you're looking for is the .html() function to change the contents of the selected div using the content available in the DOM vs. making an AJAX request.
您在原始代码中非常接近。这是对您下面的代码的修改,它按描述工作,或者至少我认为 - 我知道它可以工作,但不确定它是否满足您的要求,他们有点不清楚。显然,如果您重新加载页面,您将不得不依赖 PHP 输出的不同才能使计数器不重置。不过请注意,我不完全确定为什么要使用 .load 函数 - 该函数实际上只是 AJAX 调用的包装器,用于获取另一个页面的内容并将其插入到选定的 div 中。我相信您正在寻找的是 .html() 函数,用于使用 DOM 中可用的内容更改所选 div 的内容,而不是发出 AJAX 请求。
var timer;
$(document).ready(
name();
);
function name() {
//clear the timer
clearTimeout(timer);
//reset the timer
timer = setTimeout("name()", 1000);
//grab the current time value in the div
var time = $("#this").html();
//split times
var time_splits = time.split(":");
//add up total seconds
var total_time = (parseInt(time_splits[0])*60*60) + (parseInt(time_splits[1])*60) + parseInt(time_splits[2]);
//subtract 1 second from time
total_time -= 1;
//turn total time back in hours, minutes, and seconds
var hours = parseInt(total_time / 3600);
total_time %= 3600;
var minutes = parseInt(total_time / 60);
var seconds = total_time % 60;
//set new time variable
var new_time = (hours < 10 ? "0" : "") + hours + (minutes < 10 ? ":0" : ":" ) + minutes + (seconds < 10 ? ":0" : ":" ) + seconds;
//set html to new time
$("#this").html(new_time);
}
回答by urfusion
$dateFormat = “d F Y — g:i a”;
$targetDate = $futureDate;//Change the 25 to however many minutes you want to countdown change date in strtotime
$actualDate = $date1;
$secondsDiff = $targetDate – $actualDate;
$remainingDay = floor($secondsDiff/60/60/24);
$remainingHour = floor(($secondsDiff-($remainingDay*60*60*24))/60/60);
$remainingMinutes = floor(($secondsDiff-($remainingDay*60*60*24)-($remainingHour*60*60))/60);
$remainingSeconds = floor(($secondsDiff-($remainingDay*60*60*24)-($remainingHour*60*60))-($remainingMinutes*60));
$actualDateDisplay = date($dateFormat,$actualDate);
$targetDateDisplay = date($dateFormat,$targetDate);
<script type=”text/javascript”>
var days = <?php echo $remainingDay; ?>
var hours = <?php echo $remainingHour; ?>
var minutes = <?php echo $remainingMinutes; ?>
var seconds = <?php echo $remainingSeconds; ?>
function setCountDown(statusfun)
{//alert(seconds);
var SD;
if(days >= 0 && minutes >= 0){
var dataReturn = jQuery.ajax({
type: “GET”,
url: “<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB).'index.php/countdowncont/'; ?>”,
async: true,
success: function(data){
var data = data.split(“/”);
day = data[0];
hours = data[1];
minutes = data[2];
seconds = data[3];
}
});
seconds–;
if (seconds < 0){
minutes–;
seconds = 59
}
if (minutes < 0){
hours–;
minutes = 59
}
if (hours < 0){
days–;
hours = 23
}
document.getElementById(“remain”).style.display = “block”;
document.getElementById(“remain”).innerHTML = ” Your Product Reverse For “+minutes+” minutes, “+seconds+” seconds”;
SD=window.setTimeout( “setCountDown()”, 1000 );
}else{
document.getElementById(“remain”).innerHTML = “”;
seconds = “00″; window.clearTimeout(SD);
jQuery.ajax({
type: “GET”,
url: “<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB).'index.php/countdown/'; ?>”,
async: false,
success: function(html){
}
});
document.getElementById(“remain”).innerHTML = “”;
window.location = document.URL; // Add your redirect url
}
}
</script>
<?php
if($date1 < $futureDate && ($qtyCart > 0)){ ?>
<script type=”text/javascript”>
setCountDown();
</script>
<?php }else{ ?>
<style>
#remain{display:none;}
</style>
<?php }}?>
<div id=”remain”></div>
For more information visit urfusion
有关更多信息,请访问urfusion
回答by Haseebuddin09
@epascarello answer for your question in you need to pass the loop value in selector with id for example
$("#timer<? php echo $loopval; ?>
")
@epascarello 回答您的问题,您需要在选择器中传递带有 id 的循环值,例如 $("#timer <? php echo $loopval; ?>
")
and also call the it in the
并在
<div id="timer<?php echo $loopval; ?>">
</div>