/**
* 日志对象(构造函数)
* @param id
* @constructor
*/
function MyLogger(id) {
id = id || 'ADSLogWindow';
//私有属性
//日志窗口的DOM节点
var logWindow = null;
//私有方法
//用受保护的方法创建日志窗口
var createWindow = function () {
//取得新窗口在浏览器中居中方知识的左上角位置
var browserWindowSize = ADS.getBrowserWindowSize();
var top = ((browserWindowSize.height - 200) / 2) || 0;
var left = ((browserWindowSize.width - 200) / 2) || 0;
//创建作为日志窗口的DOM节点
//使用受保护的logWindow属性维护引用
logWindow = document.createElement('ul');
//指定ID值,以便必要时在DOM树中能够识别它
logWindow.setAttribute('id', id);
//在屏幕中居中定位日志窗口
logWindow.style.position = 'absolute';
logWindow.style.top = top + 'px';
logWindow.style.left = left + 'px';
//设置固定的大小并允许窗口内容滚动
logWindow.style.width = '200px';
logWindow.style.height = '200px';
logWindow.style.overflow = 'scroll';
//添加一些样式以美化外观
logWindow.style.padding = '0';
logWindow.style.margin = '0';
logWindow.style.border = '1px solid black';
logWindow.style.backgroundColor = 'white';
logWindow.style.listStyle = 'none';
logWindow.style.font = '10px/10px Verdana, Tahoma, Sans';
//将其添加到文档主体中
document.body.appendChild(logWindow);
};
//特权方法,(如果logWindow尚未定义,它还要调用受保护的createWindow()方法)
/**
* 向日志窗口中添加一条新纪录
* @param {String} message
* @return {Boolean}
*/
this.writeRaw = function (message) {
//如果初始的窗口不存在,则创建它
if (!logWindow) {
createWindow();
}
//创建列表项并适当地添加样式
var li = document.createElement('li');
li.style.padding = '2px';
li.style.border = '0';
li.style.borderBottom = '1px dotted black';
li.style.margin = '0';
li.style.color = '#000';
li.style.font = '12px/14px Verdana, Tahoma, Sans';
//为日志节点添加信息
if (typeof message === 'undefined') {
li.appendChild(document.createTextNode('Message was undefined'));
} else if (typeof li.innerHTML !== 'undefined') {
//检查是否支持innerHTML
li.innerHTML = message;
} else {
li.appendChild(document.createTextNode(message));
}
//将这个条目添加到日志窗口
logWindow.appendChild(li);
return true;
};
}
//公有方法
MyLogger.prototype = {
/**
* 对message中的尖括号进行编码以便在日志窗口中显示HTML源代码
* @param {String} message
*/
write:function (message) {
//警告message为空值时
if (!message) {
return this.writeRaw('ADS.log: null message');
}
//如果message不是字符串,则尝试调用toString()方法,
//如果不存在该访问则记录对象类型
if (typeof message !== 'string') {
if (message.toString()) {
return this.writeRaw(message);
} else {
return this.writeRaw(typeof message);
}
}
//转换<和>以便innerHTML不会将message作为HTML进行解析
message = message.replace(/</g, '<').replace(/>/g, '>');
return this.writeRaw(message);
},
/**
* 向日志窗口中添加加粗,红色的条目来充当标题
* @param {String} message
* @return {Boolean}
*/
header:function (message) {
message = '<span style="color:white;background-color:black;font-weight:bold;padding:0 5px;">' + message + '</span>';
return this.writeRaw(message);
}
};
if (!window.ADS) {
window.ADS = {};
}
window.ADS.log = new MyLogger();