司徒正美的一些关于javascript的处理的兼容写法。如果不想用这些,可以直接用jQuery中的功能。如bind,unbind,$('XX'),$(document).ready()等
绑定事件
JavaScript代码
- var addEvent = function( obj, type, fn ) {
- if (obj.addEventListener)
- obj.addEventListener( type, fn, false );
- else if (obj.attachEvent) {
- obj["e"+type+fn] = fn;
- obj.attachEvent( "on"+type, function() {
- obj["e"+type+fn]();
- } );
- }
- };
另一个实现
JavaScript代码
- var addEvent = (function () {
- if (document.addEventListener) {
- return function (el, type, fn) {
- el.addEventListener(type, fn, false);
- };
- } else {
- return function (el, type, fn) {
- el.attachEvent('on' + type, function () {
- return fn.call(el, window.event);
- });
- }
- }
- })();
移除事件
JavaScript代码
- var removeEvent = function(obj, type, fn) {
- if (obj.removeEventListener)
- obj.removeEventListener( type, fn, false );
- else if (obj.detachEvent) {
- obj.detachEvent( "on"+type, obj["e"+type+fn] );
- obj["e"+type+fn] = null;
- }
- }
加载事件与脚本
JavaScript代码
- var loadEvent = function(func) {
- var oldonload = window.onload;
- if (typeof window.onload != 'function') {
- window.onload = func;
- }else {
- window.onload = function() {
- oldonload();
- func();
- }
- }
- }
阻止事件
JavaScript代码
- var cancelEvent = function(event) {
- event = event||window.event
- if (event.preventDefault) {
- event.preventDefault( );
- event.stopPropagation( );
- } else {
- event.returnValue = false;
- event.cancelBubble = true;
- }
- }
取得事件源对象
相当于Prototype.js框架的Event.element(e)
JavaScript代码
- var getTarget = function(event){
- event = event || window.event;
- var obj = event.srcElement ? event.srcElement : event.target;
- return obj
- }