日期:2014-05-16  浏览次数:20371 次

js按键频率解决event兼容性问题
JScript code

function KeyCombination() {
    this.Length = 0;
    this.Records = new Array();
}
KeyCombination.prototype.Count = function() {
    return this.Length;
}
KeyCombination.prototype.AddKeyRecord = function(recordKey) {
    if (!this.Contains(recordKey)) {
        this.Records.push(new KeyRecord(recordKey));
    }
};
KeyCombination.prototype.GetKeyRecord = function(recordKey) {
    return this.Records[this.IndexOf(recordKey)];
};
KeyCombination.prototype.Contains = function(recordKey) {
    return this.IndexOf(recordKey) > -1;
};
KeyCombination.prototype.IndexOf = function(recordKey) {
    var ind = -1;
    var r;
    for (var i=0, len=this.Records.length; i<len; i++) {
        r = this.Records[i];
        if (r.Name === recordKey) {
            ind = i;
            break;
        }
    }
    return ind
};
KeyCombination.prototype.WriteKeyRecord = function(keyCode, timeStamp) {
    if (this.IsFull())
        this.ClearAllRecords();

    var r;
    for (var i=0, len=this.Records.length; i<len; i++) {
        r = this.Records[i];
        if (r.IsEmpty()) {
            r.SetValue(keyCode, timeStamp);
            this.Length++;
            break;
        }
    }
};
KeyCombination.prototype.IsFull = function() {
    return this.Length == this.Records.length;
};
KeyCombination.prototype.ClearAllRecords = function() {
    var r;
    for (var i=0, len=this.Records.length; i<len; i++) {
        r = this.Records[i];
        r.Clear();
    }
    this.Length = 0;
};

function KeyRecord(name) {
    this.Name = name;
    this.KeyCode = null;
    this.TimeStamp = null;
}
KeyRecord.prototype.IsEmpty = function() {
    return this.KeyCode === null;
};
KeyRecord.prototype.SetValue = function(keyCode, timeStamp) {
    this.KeyCode = keyCode;
    this.TimeStamp = timeStamp;
};
KeyRecord.prototype.Clear = function() {
    this.KeyCode = null;
    this.TimeStamp = null;
};
var MAX_INTERVAL = 3000;
var keyComb = new KeyCombination();
keyComb.AddKeyRecord("first");
keyComb.AddKeyRecord("second");
document.documentElement.onkeyup = function() {
    keyComb.WriteKeyRecord(event.keyCode, new Date());
    if (keyComb.IsFull()) {
        var interval = keyComb.GetKeyRecord("second").TimeStamp - keyComb.GetKeyRecord("first").TimeStamp;
            var info = interval;
            alert(interval);
    var request =getHttpObject();
    request.open("get","http://localhost/guosai/final/final.php?keyboard="+info,true);
    request.setRequestHeader('Content-Type', 'text/xml;charset=UTF-8');
    request.send(info);
    }
};


发现event代码在FF下存在兼容性问题,求解决~

------解决方案--------------------
document.documentElement.onkeyup = function(evt) {
var event = evt || event;
keyComb.WriteKeyRecord(event.keyCode, new Date());