一段着色的代碼,但還有bug。[ 原創 ]

這是我在上個月寫的一段js代碼,有代碼還有Bug已經列出來了。但目前沒有想到較好的解決方法,請大家想想辦法!

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>xuexitie</title>
<style type="text/css">
.hl-div {
Border: #C3Ced9 1Px Solid;font-size:13px;Width: Auto;Height: Auto;
Background-Color: WhiteSmoke;margin: 0px;Overflow: Auto;Text-Align: Left;
Font-Family: "Courier New", Fixedsys, "Bitstream Vera Sans Mono", Courier, Monospace;
}
.hl-ol{background:transparent;padding: 0px 0px 0px 56px;margin:0px;word-break:break-all;overflow:hidden;}
.hl-ol li{background:white;}}

</style>
<script type="text/javascript">
/**
* 通過正則來把"文本Javascript"顯示成有顏色的"網頁版Javascript"
* Topcss V1.0 2009/02/07 QQ:419074376
*
* bug list:
* 1、字符串和註釋裏面的顏色也會發生變化
* 2、字符串會遇到\"或\'時,會提前關閉 (我試着用正則去匹配"前面的\,但是由於\"是轉義字符。所以未解決)
* 3、字符串中遇到註釋會提前結束
*/
function $(str){
if(typeof str == "string") return document.getElementById(str);
}

var formatCode = {
addStyle : function(str){
if(!str) return "";
str = str.replace(/(\<br \/\>)/g,"</li><li οnmοuseοver=\"this.style.background='#C4E8FD';\" οnmοuseοut=\"this.style.background='#fff';\">");//設置換行
str = "<div class=\"hl-div\"><ol class=\"hl-ol\"><li οnmοuseοver=\"this.style.background='#C4E8FD';\" οnmοuseοut=\"this.style.background='#fff';\">" + str + "</li></ol></div>";//加入html元素
return str;
},
javascript : function (str){
if(!str) return "";
//關鍵字字典
Objects = ["Anchor", "Applet", "Area", "Arguments", "Array", "Boolean", "Button", "Checkbox", "Collection", "Crypto", "Date", "Dictionary", "Document", "Drive", "Drives", "Element", "Enumerator", "Event", "File", "FileObject", "FileSystemObject", "FileUpload", "Folder", "Folders", "Form", "Frame", "Function", "Global", "HTMLElement", "Hidden", "History", "Image", "Infinity", "Input", "JSObject", "JavaArray", "JavaClass", "JavaObject", "JavaPackage", "Layer", "Link", "Math", "MimeType", "Navigator", "Number", "Object", "Option", "Packages", "Password", "Plugin", "PrivilegeManager", "Random", "RegExp", "Select", "String", "Submit", "Text", "Textarea", "URL", "UltraEdit", "VBArray", "WScript", "Window", "activeDocument", "screen"];
Keywords = ["abstract", "break", "byte", "case", "catch", "char", "class", "const", "continue", "default", "delete", "do", "double", "else", "extends", "false", "final", "finally", "float", "for", "function", "goto", "if", "implements", "import", "in", "instanceof", "int", "interface", "long", "native", "null", "package", "private", "protected", "public", "reset", "return", "short", "static", "super", "switch", "synchronized", "this", "throw", "transient", "true", "try", "var", "void", "while", "with"];
Methods = ["ActiveXObject", "E", "Echo", "FromPoint", "HandleEvent", "LN10", "LN2", "LOG10E", "LOG2E", "Links", "MAX_VALUE", "MIN_VALUE", "NEGATIVE_INFINITY", "NaN", "PI", "POSITIVE_INFINITY", "SQRT1_2", "SQRT2", "TYPE", "UTC", "above", "abs", "acos", "action", "activeElement", "alert", "alinkColor", "all", "altKey", "anchor", "anchors", "appCodeName", "appName", "appVersion", "applets", "apply", "arguments", "arity", "asin", "assign", "atan", "atan2", "atob", "availHeight", "availLeft", "availTop", "availWidth", "back", "background", "below", "bgColor", "big", "blink", "blur", "bold", "border", "borderWidths", "bottom", "btoa", "button", "call", "callee", "caller", "cancelBubble", "captureEvents", "ceil", "charAt", "charCodeAt", "charset", "checked", "children", "className", "classes", "clear", "clearInterval", "clearTimeout", "click", "clientInformation", "clientX", "clientY", "close", "closed", "colorDepth", "compile", "complete", "concat", "confirm", "constructir", "contains", "contextual", "cookie", "cos", "crypto", "ctrlKey", "current", "data", "defaultCharset", "defaultChecked", "defaultSelected", "defaultStatus", "defaultValue", "description", "disableExternalCapture", "disablePrivilege", "document", "domain", "element", "elements", "embeds", "enableExternalCapture", "enablePrivilege", "enabledPlugin", "encoding", "escape", "eval", "event", "exec", "exp", "expando", "fgColor", "fileName", "find", "fixed", "floor", "focus", "fontColor", "fontSize", "form", "forms", "forward", "frames", "fromCharCode", "fromElement", "get", "getAttribute", "getClass", "getDate", "getDay", "getFullYear", "getHours", "getMember", "getMilliseconds", "getMinutes", "getMonth", "getSeconds", "getSelection", "getSlot", "getTime", "getTimezoneOffset", "getUTCDate", "getUTCDay", "getUTCFullYear", "getUTCHours", "getUTCMilliseconds", "getUTCMinutes", "getUTCMonth", "getUTCSeconds", "getWindow", "getYear", "global", "go", "hash", "height", "hidden", "history", "home", "host", "hostName", "href", "hspace", "id", "ids", "ignoreCase", "images", "index", "indexOf", "inner", "innerHTML", "innerHeight", "innerText", "innerWidth", "insertAdjacentHTML", "insertAdjacentText", "isFinite", "isNaN", "italics", "java", "javaEnabled", "join", "keyCode", "lang", "language", "lastIndex", "lastIndexOf", "lastMatch", "lastModified", "lastParen", "layerX", "layerY", "layers", "left", "leftContext", "length", "link", "linkColor", "load", "location", "locationBar", "log", "lowsrc", "margins", "match", "max", "menubar", "method", "mimeTypes", "min", "modifiers", "moveAbove", "moveBelow", "moveBy", "moveTo", "moveToAbsolute", "multiline", "name", "navigate", "navigator", "netscape", "next", "number", "offscreenBuffering", "offset", "offsetHeight", "offsetLeft", "offsetParent", "offsetTop", "offsetWidth", "offsetX", "offsetY", "onHelp", "onabort", "onblur", "onchange", "onclick", "ondblclick", "ondragdrop", "onerror", "onfocus", "onkeydown", "onkeypress", "onkeyup", "onload", "onmousedown", "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onmove", "onreset", "onresize", "onsubmit", "onunload", "open", "opener", "options", "outerHTML", "outerHeight", "outerText", "outerWidth", "paddings", "pageX", "pageXOffset", "pageY", "pageYOffset", "parent", "parentElement", "parentLayer", "parentWindow", "parse", "parseFloat", "parseInt", "pathname", "personalbar", "pixelDepth", "platform", "plugins", "pop", "port", "pow", "preference", "previous", "print", "prompt", "protocol", "prototype", "push", "random", "readyState", "reason", "referrer", "refresh", "releaseEvents", "reload", "removeAttribute", "removeMember", "replace", "resizeBy", "resizeTo", "returnValue", "reverse", "right", "rightContext", "round", "screenX", "screenY", "scroll", "scrollBy", "scrollIntoView", "scrollTo", "scrollbars", "search", "select", "selected", "selectedIndex", "self", "setAttribute", "setDate", "setFullYear", "setHotkeys", "setHours", "setInterval", "setMember", "setMilliseconds", "setMinutes", "setMonth", "setResizable", "setSeconds", "setSlot", "setTime", "setTimeout", "setUTCDate", "setUTCFullYear", "setUTCHours", "setUTCMillseconds", "setUTCMinutes", "setUTCMonth", "setUTCSeconds", "setYear", "setZOptions", "shift", "shiftKey", "siblingAbove", "siblingBelow", "signText", "sin", "slice", "smallsort", "source", "sourceIndex", "splice", "split", "sqrt", "src", "srcElement", "srcFilter", "status", "statusbar", "stop", "strike", "sub", "submit", "substr", "substring", "suffixes", "sun", "sup", "systemLanguage", "tagName", "tags", "taint", "taintEnabled", "tan", "target", "test", "text", "title", "toElement", "toGMTString", "toLocaleString", "toLowerCase", "toString", "toUTCString", "toUpperCase", "toolbar", "top", "type", "unescape", "unshift", "untaint", "unwatch", "userAgent", "userLanguage", "value", "valueOf", "visibility", "vlinkColor", "vspace", "watch", "which", "width", "window", "write", "writeln"];
Cmds = ["ASCIIToUnicode", "ansiToOem", "clearClipboard", "closeFile", "collapseAll", "columnCenterJustify", "columnCut", "columnDelete", "columnInsert", "columnInsertNum", "columnLeftJustify", "columnModeOff", "columnModeOn", "columnRightJustify", "copy", "copyAppend", "copyFilePath", "cut", "cutAppend", "decryptFilePrompt", "deleteLine", "deleteText", "deleteToEndOfLine", "deleteToStartOfLine", "dosToMac", "dosToUnix", "dupeLine", "encryptFilePrompt", "endSelect", "expandAll", "findReplace", "frInFiles", "fromEBCDIC", "getString", "getValue", "gotoBookmark", "gotoBookmarkSelect", "gotoLine", "gotoLineSelect", "gotoPage", "gotoPageSelect", "hexDelete", "hexInsert", "hexOff", "hexOn", "hideOrShowLines", "insertLine", "insertMode", "insertPageBreak", "insertTemplate", "invertCase", "isChar", "isCharGt", "isColNum", "isColNumGt", "isEof", "isExt", "isFTP", "isFound", "isHexModeOn", "isName", "isNotFound", "isSel", "key", "matchBrace", "messageBox", "moveLineDown", "moveLineUp", "newFile", "oemToAnsi", "outputWindow", "overStrikeMode", "paste", "perlReOn", "previousBookmark", "previousBookmarkSelect", "reIndentSelection", "returnToWrap", "runTool", "save", "saveAll", "saveAs", "selectAll", "selectClipboard", "selectLine", "selectToBottom", "selectToTop", "selectWord", "setActive", "showWindow", "sortAsc", "sortDes", "spacesToTabs", "spacesToTabsAll", "startSelect", "tabsToSpaces", "timeDate", "toCaps", "toEBCDIC", "toLower", "toUpper", "toggleBookmark", "trimTrailingSpaces", "ueReOn", "unicodeToASCII", "unixMacToDos", "unixReOn", "wrapToReturn", "xmlConvertToCRLF"];
Porperties = ["clipboardIdx", "columnMode", "currentChar", "currentColumnNum", "currentLineNum", "currentPos", "directoryStart", "fileSize", "filesToSearch", "fromCol", "hexMode", "insOvrMode", "logChanges", "matchCase", "matchWord", "mode", "path", "preserveCase", "regExp", "regexMode", "replaceAll", "replaceInAllOpen", "searchAscii", "searchDown", "searchInColumn", "searchInFilesTypes", "searchSubs", "selectText", "selection", "showOutput", "showStatus", "toCol", "unicodeSearch", "useOutputWindow", "visible"];
Separs = ["\\(", "\\)", "\\,", "\\{", "\\}"];
Operators = ["is", "new", "sizeof", "typeof", "unchecked"];
Operatorsf = ["\\!\\=\\=", "\\!\\=", "\\!", "\\+\\+", "\\+", "\\=\\=\\=", "\\=\\=", "\\&\\&", "\\$", "\\<\\=", "\\<", "\\>\\>\\>", "\\>\\=", "\\>", "\\?", "\\[", "\\]", "\\%", "\\^", "\\|", "\\~"];
//格式化關鍵字
str = str.replace(/</g, "<").replace(/>/g, ">");//轉義<、>
str = str.replace(/(\".*?\"|\'.*?\')/g,"<span style='color:Gray;'>$1</span>");//設置字符串
str = str.replace(/\b([0-9]+)\b/g, "<span style='color:#ff0000;'>$1</span>");//設置數字
str = str.replace(/(\/\/.*|\/\*[\s\S]*?\*\/)/g,"<span style='color:#008080;'>$1</span>");//設置註釋
str = str.replace(eval("/(" + Separs.join("|") + ")/g"),"<span style='color:#af4040;'>$1</span>");//括號
str = str.replace(eval("/\\b(" + Objects.join("|") + ")\\b/g"),"<span style='color:#ff0000;'>$1</span>");
str = str.replace(eval("/\\b(" + Keywords.join("|") + "|" + Cmds.join("|") + "|" + Porperties.join("|") + ")\\b/g"),"<span style='color:#0000ff;'>$1</span>");
str = str.replace(eval("/\\b(" + Methods.join("|") + ")\\b/g"),"<span style='color:#ff8000;'>$1</span>");
str = str.replace(eval("/\\b(" + Operators.join("|") + ")\\b/g"),"<span style='color:#008000;'>$1</span>");
str = str.replace(eval("/(" + Operatorsf.join("|") + ")/g"),"<span style='color:#008000;'>$1</span>");
str = str.replace(/ | /g,"  ");//設置空格和Tab符號
str = str.replace(/(\n)/g,"<br />");
return str;
},
css : function(str){

}
}

window.onload = function(){
//字符串來源
var str = $("codes").value;
//顯示代碼執行結果
$("discode").innerHTML = formatCode.addStyle( formatCode.javascript( str ) );
}


</script>
</head>
<body>
<textarea id="codes" style="display:none;">
/* attach methods */
(function(){
/* BdBrowser scope */
var ua = navigator.userAgent.toLowerCase();

var isStrict = document.compatMode == "CSS1Compat",
isOpera = ua.indexOf("opera") > -1,
isSafari = (/webkit|khtml/).test(ua),
isSafari3 = isSafari && ua.indexOf('webkit/5') != -1,
isIE = !isOpera && ua.indexOf("msie") > -1,
isIE7 = !isOpera && ua.indexOf("msie 7") > -1,
isGecko = !isSafari && ua.indexOf("gecko") > -1,
isBorderBox = isIE && !isStrict,
isWindows = (ua.indexOf("windows") != -1 || ua.indexOf("win32") != -1),
isMac = (ua.indexOf("macintosh") != -1 || ua.indexOf("mac os x") != -1),
isAir = (ua.indexOf("adobeair") != -1),
isLinux = (ua.indexOf("linux") != -1),
isSecure = window.location.href.toLowerCase().indexOf("https") === 0;

// remove css image flicker
if(isIE && !isIE7){
try{
document.execCommand("BackgroundImageCache", false, true);
}catch(e){}
}

var browsers = {
isOpera : isOpera,
isSafari : isSafari,
isSafari3 : isSafari3,
isSafari2 : isSafari && !isSafari3,
isIE : isIE,
isIE6 : isIE && !isIE7,
isIE7 : isIE7,
isGecko : isGecko,
isBorderBox : isBorderBox,
isLinux : isLinux,
isWindows : isWindows,
isMac : isMac,
isAir : isAir
};

for(var p in browsers){
BdBrowser[p] = browsers[p];
}

/* BdElement scope */
window.Bd$ = BdElement.check = function(id){
return typeof id == 'string' ? document.getElementById(id) : id;
}

BdElement.removeNode = isIE ? function(){
var d;
return function(node){
if(node && node.tagName != 'BODY'){
d = d || document.createElement('DIV');
d.appendChild(node);
d.innerHTML = '';
}
}
}() : function(node){
if(node && node.parentNode && node.tagName != 'BODY'){
node.parentNode.removeChild(node);
}
}

/* BdEvent scope */
BdEvent.addEvent = function(el, fn, handler){
if(isIE){
el.attachEvent("on" + fn, handler);
}else{
el.addEventListener(fn, handler, false);
}
}

BdEvent.removeEvent = function(el, fn, handler){
if(isIE){
el.detachEvent("on" + fn, handler);
}else{
el.removeEventListener(fn, handler, false);
}
}

BdEvent.addDOMLoadEvent = (function(){
// create event function stack
var load_events = [],
load_timer,
script,
done,
exec,
old_onload,
init = function () {
done = true;
// kill the timer
clearInterval(load_timer);

// execute each function in the stack in the order they were added
while (exec = load_events.shift())
setTimeout(exec, 10);
if (script) script.onreadystatechange = '';
};

return function (func) {
// if the init function was already ran, just run this function now and stop
if (done) return func();


if (!load_events[0]) {
// for Mozilla/Opera9
if (document.addEventListener)
document.addEventListener("DOMContentLoaded", init, false);

// for Internet Explorer

/*@cc_on @*/
/*@if (@_win32)
document.write("<script id=__ie_onload defer src=//0><\/scr"+"ipt>");
script = document.getElementById("__ie_onload");
script.onreadystatechange = function() {
if (this.readyState == "complete")
init(); // call the onload handler
};
/*@end @*/


// for Safari
if (/WebKit/i.test(navigator.userAgent)) { // sniff
load_timer = setInterval(function() {
if (/loaded|complete/.test(document.readyState))
init(); // call the onload handler
}, 10);
}

// for other browsers set the window.onload, but also execute the old window.onload
old_onload = window.onload;

window.onload = function() {
init();
if (old_onload) old_onload();
};
}

load_events.push(func);
}
})();

/* BdUtil scope */
BdUtil.insertWBR = (function(){
var textAreaCache = null;

function getContainer(){
var textarea = document.getElementById('insertWBR_container');
if(!textarea){
textarea = document.createElement('TEXTAREA');
textarea.id = 'insertWBR_container';
textarea.style.display = 'none';
document.body.insertBefore(textarea, document.body.firstChild);
}
return (textAreaCache = textarea)
}

return function(text, step){
var textarea = textAreaCache || getContainer();
if(!textarea) return text;

textarea.innerHTML = text.replace(/&/g,'&').replace(/</g,"<").replace(/>/g,">");
var string = textarea.value;


var step = (step || 5), reg = new RegExp("(\\S{" + step + "})", "gi");
var result = string.replace(/(<[^>]+>)/gi,"$1<wbr/>").replace(/(>|^)([^<]+)(<|$)/gi, function(a,b,c,d){
if(c.length < step) return a;
return b + c.replace(reg, "$1<wbr/>") + d;
}).replace(/&([^;]*)(<wbr\/?>)([^;]*);/g,'&$1$3;');
return result;
}
})();

BdUtil.hi_tracker = (function(){
function E(s){ return encodeURIComponent(s) }

function tracker(mn, a){
return function(){
var t = new Date().getTime(),
href = a.href;
if(isIE){
var regex = /href\s*=\s*("|')?([^\s]*)\1/gi;
if(regex.test(a.outerHTML))
href = RegExp.$2;
}
new Image().src = "http://hi.baidu.com/sys/statlog/1.gif?m=" + E(mn) + "&v=" + E(href) + "&t="+t;
}
}

return function(mod_id_or_el, mod_name){
var bl = (typeof mod_id_or_el == 'string'),
el = bl ? document.getElementById(mod_id_or_el) : mod_id_or_el,
mn = mod_name || (bl ? mod_id_or_el : el.tagName),
as = el.nodeName.toUpperCase() == 'A' ? [el] : el.getElementsByTagName('A');
if(!as || as.length <= 0) return false;
for(var i = 0, j = as.length; i < j; i ++){
var a = as[i];
isIE ? a.attachEvent("onclick", tracker(mn, a)) : a.addEventListener("click", tracker(mn, a), false);
}
}
})();

/* BdAjax scope */
BdAjax.getXHR = function(){
var xhr = null;
try{
return (xhr = new XMLHttpRequest());
}catch(e){}

for(var i = 0, a = ['MSXML3','MSXML2','Microsoft']; i < a.length; i ++){
try{
xhr = new ActiveXObject(a[i]+'.XMLHTTP');
break;
}catch(e){}
}

return xhr;
}

BdAjax.request = function(url, json){
var xhr = this.getXHR();
if(!xhr){
throw new Error("cant't initialize xhr instance.");
}
var options={};
options.method = (json.method || 'get').toLowerCase();
options.asyn = true;
options.onSuccess = json.onSuccess || function(){};
options.onFailure = json.onFailure || function(){ new Image().src = "/sys/statlog/1.gif?m=ajax-request&v=" + encodeURIComponent(url) + "&t=" + new Date().getTime();};


options.postData = json.postData || null;

xhr.open(options.method, url, options.asyn);

if("post" == options.method.toLowerCase()){
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}

xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status == 0 || xhr.status == 200){
options.onSuccess(xhr);
}else{
options.onFailure(xhr);
}
}
}
xhr.send(options.postData);
}

BdAjax.loadJS=(function()
{
var head ;
return function(jsUrl){
head = head || document.getElementsByTagName("head")[0];
var s=document.createElement("script");
s.type="text/javascript";
s.src=jsUrl;
head.appendChild(s);
}

})();

BdString.trim=function(str)
{
return str.replace(/(^[\s\t\xa0\u3000]+)|([\u3000\xa0\s\t]+$)/g, "");
}
BdString.byteLength = function(str){
return str.replace(/[^\x00-\xFF]/g, "ly").length;
}
BdString.subByte = function(s, n){
if(this.byteLength(s)<=n)
return s;
for(var i=Math.floor((n=n-2)/2),l=s.length; i<l; i++)
if(this.byteLength(s.substr(0,i))>=n)
return s.substr(0,i) +"\u2026";
return s;
}
})();
function setActiveStyleSheet(title) {
var i, a, main;
for(i=0; (a = document.getElementsByTagName("link")[i]); i++) { /*a是所有的link元素*/
if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {/*檢查1.是不是樣式表2.有沒有title*/
a.disabled = true;/*如果有title就禁用*/
if(a.getAttribute("title") == title) a.disabled = false;/*如果等於當前設置的title,則激活*/
}
}
}
function getActiveStyleSheet() {
var i, a;
for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
/*a是所有的link元素,如果a是style並且有title,沒有被禁用,則判定其爲當前活躍樣式,返回它的title*/
}
return null;
}

function getPreferredStyleSheet() {
var i, a;
for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if(a.getAttribute("rel").indexOf("style") != -1/*是樣式表*/
&& a.getAttribute("rel").indexOf("alt") == -1/*不是替代樣式表*/
&& a.getAttribute("title")/*有title*/
) return a.getAttribute("title");/*滿足以上三個條件,返回title*/
}
return null;
}
/*以下爲設置cookie的函數,不研究*/
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
/*以上爲設置cookie的函數,不研究*/


window.onload = function(e) {
var cookie = readCookie("style");
var title = cookie ? cookie : getPreferredStyleSheet();
setActiveStyleSheet(title);
}
/*讀取style的cookie,如果有cookie則title=cookie,否則執行getPreferredStyleSheet()函數。最後根據title設置文檔當前樣式。*/


window.onunload = function(e) {
var title = getActiveStyleSheet();
createCookie("style", title, 365);
}


/*JS for the navigation of the header*/
navHover = function() {
var lis = document.getElementById("mainNav").getElementsByTagName("LI");
for (var i=0; i<lis.length; i++) {
lis[i].οnmοuseοver=function() {
this.className+=" iehover";
}
lis[i].οnmοuseοut=function() {
this.className=this.className.replace(new RegExp(" iehover\\b"), "");
}
}
}
if (window.attachEvent) window.attachEvent("onload", navHover);

/*To change the font size of the content area.*/
function changeFont(a){
size = a + "px";
document.getElementById("content").style.fontSize = size;
}
function changeFont12(){changeFont(12);return false;}
function changeFont14(){changeFont(14);return false;}
function changeFont16(){changeFont(16);return false;}
function addFontButton(){
//添加按鈕
var contentDIV = document.getElementById("content");
var title = document.getElementById("title");
var fontForm = document.createElement('form');
var para = document.createElement('p');
var paraText = document.createTextNode('改變內容文字大小:');
para.appendChild(paraText);
para.id = "changeFont";
fontForm.appendChild(para);
contentDIV.insertBefore(fontForm,title);

var button12 = document.createElement('button');
var button12Text = document.createTextNode('12像素');
button12.appendChild(button12Text);
button12.onclick = changeFont12;
var changeFont = document.getElementById("changeFont");
changeFont.appendChild(button12);

var button14 = document.createElement('button');
var button14Text = document.createTextNode('14像素');
button14.appendChild(button14Text);
button14.onclick = changeFont14;
changeFont.appendChild(button14);

var button16 = document.createElement('button');
var button16Text = document.createTextNode('16像素');
button16.appendChild(button16Text);
button16.onclick = changeFont16;
changeFont.appendChild(button16);
}
function mainStyle(){
setActiveStyleSheet('main');
return false;
}
function whiteStyle(){
setActiveStyleSheet('alt');
return false;
}
function addStyleSwitcher(){
var sideBar = document.getElementById("sideBar");
var styleBox = document.createElement('div');
styleBox.className = "box";
var styleTitle = document.createElement('h2');
var titleText = document.createTextNode('站點風格');
styleTitle.appendChild(titleText);
styleBox.appendChild(styleTitle);//添加標題
var styleUL = document.createElement('ul');
//默認風格
var liMain = document.createElement('li');
var aMain = document.createElement('a');
aMain.href = '#';
aMain.onclick = mainStyle;
var aMainText = document.createTextNode('默認風格');
aMain.appendChild(aMainText);
liMain.appendChild(aMain);
styleUL.appendChild(liMain);
//全白風格
var liWhite = document.createElement('li');
var aWhite = document.createElement('a');
aWhite.href = '#';
aWhite.onclick = whiteStyle;
var aWhiteText = document.createTextNode('全白');
aWhite.appendChild(aWhiteText);
liWhite.appendChild(aWhite);
styleUL.appendChild(liWhite);
styleBox.appendChild(styleUL);//添加切換樣式列表
sideBar.appendChild(styleBox);
}
window.onload = function(e) {
var cookie = readCookie("style");
var title = cookie ? cookie : getPreferredStyleSheet();
setActiveStyleSheet(title);
addFontButton();//添加控制字體大小按鈕
addStyleSwitcher();
}

</textarea>
<div id="discode"></div>

</body>
</html>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章