這是一篇長期累積的片段集,涵蓋 this 綁定、HTTP 請求、表單操作、游標控制、打印、Cookie、正則與尺寸計算等主題。以下依功能分類整理,並保留可運用的關鍵程式碼。
理解這兩個方法最好的方式,就是自己寫一遍:
Function.prototype.apply = function (obj, argu) {
if (obj) obj.constructor.prototype._caller = this;
var argus = new Array();
for (var i = 0; i < argu.length; i++) argus[i] = "argu[" + i + "]";
var r;
eval("r = " + (obj ? ("obj._caller(" + argus.join(",") + ");")
: ("this(" + argus.join(",") + ");")));
return r;
};
Function.prototype.call = function (obj) {
var argu = new Array();
for (var i = 1; i < arguments.length; i++) argu[i - 1] = arguments[i];
return this.apply(obj, argu);
};
這段程式用 eval 拼字串呼叫,示範性質大於實用價值;真實專案請直接用原生的 call / apply / bind。
XMLHttpRequest 的 readyState 表示請求進度:0 = 未初始化,1 = 已載入(連線建立),2 = 已送出,3 = 運行中,4 = 完成。只有在 4 且 status 為 200 時,才能安全讀取回應內容。
function CheckURL(URL) {
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.Open("GET", URL, false);
try {
xmlhttp.Send();
var result = xmlhttp.status;
} catch (e) { return false; }
if (result == 200) return true;
xmlhttp = null;
return false;
}
這裡用的是同步請求,會鎖住整個執行緒,僅適合極短的檢查;正式環境請改非同步並加上逾時處理。
var a = location.search.substr(1);
if (a.length > 0) {
var re = /([^&]*?)\=([^&]*)/g;
var s = a.match(re);
for (var i = 0; i < s.length; i++) {
alert(s[i] + " → " + s[i].split("=")[1]);
}
}
現在直接用 URLSearchParams 即可:new URLSearchParams(location.search).get('a')。
function getCaret(textbox) {
var control = document.activeElement;
textbox.focus();
var rang = document.selection.createRange();
rang.setEndPoint("StartToStart", textbox.createTextRange());
control.focus();
return rang.text.length;
}
function setCaret(textbox, pos) {
try {
var r = textbox.createTextRange();
r.moveStart('character', pos);
r.collapse(true);
r.select();
} catch (e) {}
}
這組程式依賴 IE 的 TextRange。現代瀏覽器請改用 setSelectionRange(start, end),一行就能完成同樣的事。
var flag = false;
function DrawImage(ImgD) {
var image = new Image();
var iwidth = 80, iheight = 80; // 允許的最大寬高
image.src = ImgD.src;
if (image.width > 0 && image.height > 0) {
flag = true;
if (image.width / image.height >= iwidth / iheight) {
if (image.width > iwidth) {
ImgD.width = iwidth;
ImgD.height = (image.height * iwidth) / image.width;
} else {
ImgD.width = image.width; ImgD.height = image.height;
}
} else {
if (image.height > iheight) {
ImgD.height = iheight;
ImgD.width = (image.width * iheight) / image.height;
} else {
ImgD.width = image.width; ImgD.height = image.height;
}
}
ImgD.alt = image.width + "×" + image.height;
}
}
呼叫方式:<img src="..." onload="DrawImage(this)" />。今天直接用 CSS 的 max-width:100%;height:auto 就能達到相同效果。
document.body.clientWidth / clientHeight // 可見區域(不含邊框) document.body.offsetWidth / offsetHeight // 含邊框與捲軸 document.body.scrollWidth / scrollHeight // 內容整體尺寸 document.body.scrollTop / scrollLeft // 已捲動的距離 window.screenTop / screenLeft // 視窗在螢幕上的位置 window.screen.width / height // 螢幕解析度 window.screen.availWidth / availHeight // 可用工作區
匹配中文字符: /[\u4e00-\u9fa5]/ 匹配雙位元組字符: /[^\x00-\xff]/ 匹配空行: /\n[\s| ]*\r/ 匹配 HTML 標籤: /<(.*)>.*<\/\1>|<(.*) />/ 匹配首尾空白: /(^\s*)|(\s*$)/ 匹配 Email: /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/ 匹配 URL: /http:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&]*)?/
限制輸入框只能填中文:onkeyup="value=value.replace(/[^\u4E00-\u9FA5]/g,'')";只能填數字:onkeyup="value=value.replace(/[^\d]/g,'')"。
function SetCookie(sName, sValue) {
document.cookie = sName + "=" + escape(sValue) + "; ";
}
function GetCookie(sName) {
var aCookie = document.cookie.split("; ");
for (var i = 0; i < aCookie.length; i++) {
var aCrumb = aCookie[i].split("=");
if (sName == aCrumb[0]) return unescape(aCrumb[1]);
}
}
function DelCookie(sName) {
document.cookie = sName + "=; expires=Fri, 31 Dec 1999 23:59:59 GMT;";
}
舊版 IE 的 setTimeout 不支援額外參數,常見解法是改寫它:
var _st = window.setTimeout;
window.setTimeout = function (fRef, mDelay) {
if (typeof fRef == 'function') {
var argu = Array.prototype.slice.call(arguments, 2);
var f = (function () { fRef.apply(null, argu); });
return _st(f, mDelay);
}
return _st(f, mDelay);
};
window.setTimeout(function (x) { alert(x); }, 1000, 'fason');
現代的 setTimeout 本身已支援第三個參數之後逐一傳入,不必再繞這一層。
這份清單裡有相當比例是 IE 專屬 API(ActiveXObject、TextRange、dataurl、execCommand 等),在今天的專案中已不適用。但它們背後想解決的需求——檢查資源、控制游標、縮放圖片、讀寫 Cookie、傳遞計時器參數——全都還在,只是每個都有了更乾淨的標準寫法。把需求記住,比記住舊 API 更有價值。