第一个应用实现了类似下载Firefox扩展之前,3秒倒计时的“安装”按钮的功能。第二个应用实现了在倒计时的同时,用背景色表示“压力”程度,一开始是淡黄色,逐渐转变成更有紧迫感的红色。两个应用都是基于prototype库,另外还用到了Stoyan Stefanov写的rgbcolor.js——一个实用的将字符串转换为Hex、RGB等格式色彩的javascript类。
倒计时按钮包括函数buttonCountdown,输入倒计时秒数,按钮的element或id,倒数时候的标签。
代码:buttonCountdown
function buttonCountdown(seconds, element, label) {
if (typeof element == 'string') element = $(element);
element.disabled = true;
Element.addMethods({
updateButton: function(num, sec, elt, lab) {
var remaining = sec - num;
if (remaining == 0) {
elt.value = lab;
elt.disabled = false;
} else {
elt.value = lab + " (" + remaining + ")";
}
},
});
if (element.tagName == 'BUTTON' || 'INPUT') {
for (var i = 0; i <= seconds; i++) {
Element.updateButton.delay(i, i, seconds, element, label);
}
}
}
背景色渐变倒计时包含两个函数divisionCountdown和CalculatePresentColor。divisionCountdown和buttonCountdown类似,输入秒数,element或id,标签。CalculatePresentColor输入倒计时的百分比,倒计时开始时和结束时的色彩。
代码:divisionCountdown和CalculatePresentColor
var START_COLOR = "#fff1a8";
var END_COLOR = "#b31e1e";
function divisionCountdown(seconds, element, label) {
if (typeof element == 'string') element = $(element);
Element.addMethods({
updateDivision: function(num, sec, elt, lab) {
elt.style.backgroundColor = calculatePresentColor(
Math.round(num / sec * 100), START_COLOR, END_COLOR
);
var remaining = Math.round(sec - num);
if (remaining == 0) {
elt.innerHTML = lab.toUpperCase();
} else {
elt.innerHTML = lab + " (" + remaining + ")";
}
},
});
if (element.tagName == 'DIV') {
for (var i = 0; i <= seconds; i+=0.1) {
Element.updateDivision.delay(i, i, seconds, element, label);
}
}
}
function calculatePresentColor(percentage, startColor, endColor) {
startColor = new RGBColor(startColor);
endColor = new RGBColor(endColor);
if (startColor.ok && endColor.ok) {
var r = Math.round(startColor.r > endColor.r ?
startColor.r - Math.abs(startColor.r - endColor.r) * percentage / 100 :
startColor.r + Math.abs(startColor.r - endColor.r) * percentage / 100);
var g = Math.round(startColor.g > endColor.g ?
startColor.g - Math.abs(startColor.g - endColor.g) * percentage / 100 :
startColor.g + Math.abs(startColor.g - endColor.g) * percentage / 100);
var b = Math.round(startColor.b > endColor.b ?
startColor.b - Math.abs(startColor.b - endColor.b) * percentage / 100 :
startColor.b + Math.abs(startColor.b - endColor.b) * percentage / 100);
return 'rgb(' + r + ', ' + g + ', ' + b + ')';
}
}


0 评论:
发表评论
欢迎留言