资讯的台湾大选专题要求在开票当天能对票选结果实时动态显示,不过到最后,时间根本不够,功能需求已经被砍掉不少。效果看这里。代码写得比较乱,里面最主要的一个东西是SmoothSlide这个对象。

function SmoothSlide(params){
    this.element = null;
    this.intervalId = 0;
    this.params = params==null ? {}:params;
    this.onComplete = null;
    this.onProcess = null;
    this.properties = {
        holder:'vertical',
        isVertical:true,
        max:100,
        step:1,
        speed:30
    };
}

其中properties中是一些可配置的属性,onComplete和onProcess分别是结束执行和正在执行时的处理函数。 在SmoothSlide的prototype中,compute函数负责将投票数量百分比进行展示。

SmoothSlide.prototype ={
    isFunction:function( fn ) {
        return !!fn && typeof fn != "string" && !fn.nodeName 
        && fn.constructor != Array && /function/i.test( fn + "" );
    },
    clear:function(){ clearInterval(this.intervalId); },
    complete:function(){
        this.clear();
        if(this.isFunction(this.onComplete)) 
            this.onComplete(this); 
    },
    process:function(){
        if(this.isFunction(this.onProcess)) 
            this.onProcess(this);
    },
    start:function(){
        var _ = this;
        _.intervalId = setInterval(function(){
            _.compute.apply(_,[_.properties.max]);
        },
        _.properties.speed);
    },
    compute:function(max){
        var o = this.element.style;
        if(this.properties.isVertical){
            if(parseInt(o.height) >= max){    this.complete(); }
            else {
                o.height = parseInt(o.height)+this.properties.step+'%';
                this.process();
            }
        } else {
            if(parseInt(o.width) >= max){ this.complete(); }
            else {
                o.width = parseInt(o.width)+this.properties.step+'%';
                this.process();
            }
        }
    },
    init:function(){
        for(var i in this.params)
            this.properties[i] = this.params[i];
        this.element=$(this.properties.holder);    
        this.start();
    }
}

从后台获取数据的时候采取JSONP的方式,负责应用开发的同事会给我一个类似taiwanvote({...})的javascript脚本输出,得到JSON的数据以后就可以执行处理函数了.

因为页面需要定时刷新,所以还得增加一个函数定时将该脚本append到head标签中。代码如下:

var headScript = null, isAppended = false;
function appendRequestScript(url){
    var head = document.getElementsByTagName('HEAD')[0];
    if(isAppended)
        head.removeChild(headScript);
    headScript = document.createElement('SCRIPT');
    headScript.src = url+'?'+new Date().getTime();
    head.appendChild(headScript);
    isAppended = true;
}
window.onload = function(){
    var scriptUrl = 'tw2008vote.js';
    var refreshTime = 15000;
    appendRequestScript(scriptUrl);
    setInterval(function(){appendRequestScript(scriptUrl);},refreshTime);
}