Jump to content

Отсчет дней до нового года


q0p
 Share

Recommended Posts

Думаю многим знаком новогодний скин White Christmas.

Хотелось бы имеющийся в нем счетчик нормально русифицировать (т.е. сделать нормальное склонение дней (дня, день), часов, минут и секунд).

В самом шаблоне вот такой код.

<script language="JavaScript">
TargetDate = "01/01/2015 00:00";
BackColor = "";
ForeColor = "#000000";
CountActive = true;
CountStepper = -1;
LeadingZero = true;
DisplayFormat = "<b>До Нового года осталось</b> %%D%% Дней, %%H%% Часов, %%M%% Минут, %%S%% Секунд <b></b>";
FinishMessage = "<b>Ураааа! С Новым годом, товарищи!</b>";
</script>

Как его можно грамотно допилить?

post-30326-0-24753300-1416772503_thumb.jpg

Link to comment
Share on other sites

В таком виде никак. Сначала нужно рассчитать дату, потом склонять, а для этого, судя по всему, придется переписать скрипт.

Link to comment
Share on other sites

<script type='text/javascript'>

TargetDate = "01/01/2015 00:00";
BackColor = "";
ForeColor = "#000000";
CountActive = true;
CountStepper = -1;
LeadingZero = true;
Decline = true;
DisplayFormat = "<b>До Нового года осталось</b> %%D%%, %%H%%, %%M%%, %%S%%";
FinishMessage = "<b>Ураааа! С Новым годом, товарищи!</b>";

</script>

 

function declOfNum(number, type){
type = type.toUpperCase();
var declin ={
	D: ['день', 'дня', 'дней'],
	H: ['час', 'часа', 'часов'],
	M: ['минута', 'минуты', 'минут'],
	S: ['секунда', 'секунды', 'секунд'],
};

var cases = [2, 0, 1, 1, 1, 2];
return declin[type][ (number%100 > 4 && number%100 < 20) ? 2 : cases[(number%10 < 5) ? number%10 : 5] ];
}

function calcage(secs, num1, num2, type) {
var s = ((Math.floor(secs/num1))%num2).toString();
if (LeadingZero && s.length < 2){
	s = "0"+s;
}
return "<b>"+s+"</b>"+((Decline && type) ? ' '+declOfNum(parseInt(s), type) : '');
}

function CountBack(secs) {
if (secs < 0) {
	document.getElementById("cntdwn").innerHTML = FinishMessage;
	return;
}
var DisplayStr;
DisplayStr = DisplayFormat.replace(/%%D%%/g, calcage(secs,86400,100000, 'D'));
DisplayStr = DisplayStr.replace(/%%H%%/g, calcage(secs,3600,24, 'H'));
DisplayStr = DisplayStr.replace(/%%M%%/g, calcage(secs,60,60, 'M'));
DisplayStr = DisplayStr.replace(/%%S%%/g, calcage(secs,1,60, 'S'));

document.getElementById("cntdwn").innerHTML = DisplayStr;
if (CountActive){
	setTimeout("CountBack(" + (secs+CountStepper) + ")", SetTimeOutPeriod);
}
}

function putspan(backcolor, forecolor) {
document.write("<span id='cntdwn' style='background-color:"+backcolor+"; color:"+forecolor+ "'></span>");
}

var defaultValues = {
BackColor: "white",
ForeColor: "black",
TargetDate: "1/1/2015 00:00",
DisplayFormat: "%%D%%, %%H%%, %%M%%, %%S%%.",
CountActive: true,
FinishMessage: "Happy new year, anchousi! (.)(.)",
CountStepper: -1,
LeadingZero: true,
Decline: true,
};
for(var key in defaultValues){
if(typeof(window[key]) == "undefined"){
	window[key] = defaultValues[key];
}
}

CountStepper = Math.ceil(CountStepper);
if (CountStepper == 0)
CountActive = false;

var SetTimeOutPeriod = (Math.abs(CountStepper)-1)*1000 + 990;
putspan(BackColor, ForeColor);

var dthen = new Date(TargetDate);
var dnow = new Date();
if(CountStepper > 0)
ddiff = new Date(dnow-dthen);
else
ddiff = new Date(dthen-dnow);
gsecs = Math.floor(ddiff.valueOf() / 1000);
CountBack(gsecs);

  • Upvote 1
Link to comment
Share on other sites

Прикрепление полной версии globaltemplate поможет решению проблемы?

Просто я раньше пробовал готовые скрипты, которые при добавлении в конец (перед закрывающими тегами) отрабатывали нормально, но конкретно в этом месте работать отказались.

Link to comment
Share on other sites

Этот скрипт состоит из двух частей. Первая часть - определение параметров, и вторая часть которая подключается из файла, обычно находится чуть ниже первой части (вы вообще смотрите что добавляете, а если там предлагается какой нибудь вредоносный файл подключить?). Вот в этом js файле нужно заменить код из второго блока.

Link to comment
Share on other sites

Смотрю конечно, но принцип обработки кода всё равно до конца не понимаю.

Ниже идет вызов этого файла, похоже как раз этого счетчика:

<script language="JavaScript" src="{$this->settings['img_url']}/js/countdown.js"></script>

То есть остальные правки в нём?

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...