做前端久了,手邊總會積累一批零散但很好用的小技巧。這篇就把它們整理在一起,方便日後查閱,也順便分享給需要的朋友。
事件源對象:event.srcElement.tagName / event.srcElement.type
捕獲與釋放:event.srcElement.setCapture(); event.srcElement.releaseCapture();
按鍵信息:event.keyCode / event.shiftKey / event.altKey / event.ctrlKey
事件返回值:event.returnValue
鼠標位置:event.x / event.y
窗體活動元素:document.activeElement
綁定事件:document.captureEvents(Event.KEYDOWN);
訪問窗體元素:document.all("txt").focus(); document.all("txt").select();
窗體命令:document.execCommand
窗體 COOKIE:document.cookie
菜單事件:document.oncontextmenu
創建元素:document.createElement("SPAN");
根據鼠標獲得元素:document.elementFromPoint(event.x, event.y).tagName == "TD"
窗體圖片:document.images[索引]
窗體事件綁定:document.onmousedown = scrollwindow;
元素集合:document.forms.elements[索引]
對象解綁事件:document.all.xxx.detachEvent('onclick', a);
插件數目:navigator.plugins
取變量類型:typeof($js_libpath) == "undefined"
下拉框:下拉框.options[索引] / 下拉框.options.length
查找對象:document.getElementsByName("r1"); document.getElementById(id);
定時:timer = setInterval('scrollwindow()', delay); clearInterval(timer);
UNCODE 編碼:escape(), unescape
父對象:obj.parentElement (dhtml) / obj.parentNode (dom)
交換表的行:TableID.moveRow(2, 1)
替換 CSS:document.all.csss.href = "a.css";
並排顯示:display:inline
隱藏焦點:hidefocus=true
根據寬度換行:style="word-break:break-all"
快速轉到位置:obj.scrollIntoView(true)
網頁傳遞參數:location.search();
可編輯:obj.contenteditable = true
雙字節字符:/[^\x00-\xff]/
漢字:/[\u4e00-\u9fa5]/
獲得 style 內容:obj.style.cssText
HTML 標簽:document.documentElement.innerHTML
第一個 style 標簽:document.styleSheets[0]
style 裡的第一個樣式:document.styleSheets[0].rules[0]
上一網頁源:document.referrer
釋放內存:CollectGarbage();
<a href="javascript:void(0)">word</a>
<meta HTTP-EQUIV="refresh" CONTENT="8;URL=https://c98.yeah.net"> <a href="mailto:aaa@bbb.com?subject=ccc&body=xxxyyy">發郵件</a> <a name="first"></a> <a href="#first">anchors</a>
/* 讓英文字符串超出表格寬度自動換行 */ word-wrap: break-word; word-break: break-all; /* 文字超出省略 */ overflow: hidden; text-overflow: ellipsis;
<IFRAME src="1.htm" width=300 height=180 allowtransparency></iframe>
禁止粘貼:<input type=text onpaste="return false"> 關閉輸入法:<input style="ime-mode:disabled"> 自動全選:<input type=text name=text1 value="123" onfocus="this.select()"> ENTER 跳到下一個輸入框:<input onkeydown="if(event.keyCode==13)event.keyCode=9"> 文本框默認值:<input type=text value="123" onfocus="alert(this.defaultValue)"> 自動完成:<input type=text autocomplete=on> 開啟 / autocomplete=off 關閉
document.oncontextmenu = function() { return false; }
<body oncontextmenu="return false" ondragstart="return false" onselectstart="return false" onselect="document.selection.empty()" oncopy="document.selection.empty()" onbeforecopy="return false" onmouseup="document.selection.empty()"> <noscript><iframe src="*.htm"></iframe></noscript>
<link rel="Shortcut Icon" href="favicon.ico"> <link rel="Bookmark" href="favicon.ico">
favicon.ico 名字最好不要改,尺寸 16*16、16 色,放在虛擬目錄根目錄下。
<input type=button value=查看網頁源代碼 onclick="window.location = 'view-source:'+ 'https://www.csdn.net/'">
obj.title = "123
sdfs ";
var n1 = new Date("2004-10-10".replace(/-/g, "\/")).getTime();
document.selection.createRange().duplicate().text
<body onload="window.resizeTo(window.screen.width - 4, window.screen.height - 50); window.moveTo(-4, -4)">
window.open("aa.htm", "meizz", "fullscreen=7");
alert(decodeURIComponent(encodeURIComponent("https://你好.com?as= hehe")))
encodeURIComponent 會把 ":"、"/"、";" 和 "?" 一起編碼。
<tr onmouseover="this.bgColor='#f0f0f0'" onmouseout="this.bgColor='#ffffff'">
s += "\r\n網頁可見區域寬:" + document.body.clientWidth; s += "\r\n網頁可見區域高:" + document.body.clientHeight; s += "\r\n網頁可見區域高(含邊線):" + document.body.offsetWidth; s += "\r\n網頁正文全文寬:" + document.body.scrollWidth; s += "\r\n網頁正文全文高:" + document.body.scrollHeight; s += "\r\n網頁被卷去的高:" + document.body.scrollTop; s += "\r\n網頁被卷去的左:" + document.body.scrollLeft; s += "\r\n網頁正文部分上:" + window.screenTop; s += "\r\n網頁正文部分左:" + window.screenLeft; s += "\r\n屏幕分辨率的高:" + window.screen.height; s += "\r\n屏幕分辨率的寬:" + window.screen.width; s += "\r\n屏幕可用工作區高度:" + window.screen.availHeight; s += "\r\n屏幕可用工作區寬度:" + window.screen.availWidth;
<input type=text onkeypress="return event.keyCode>=48&&event.keyCode<=57||(this.value.indexOf('.')<0?event.keyCode==46:false)" onpaste="return !clipboardData.getData('text').match(/\D/)" ondragenter="return false">
<META HTTP-EQUIV="pragma" CONTENT="no-cache"> <META HTTP-EQUIV="Cache-Control" CONTENT="no-cache, must-revalidate"> <META HTTP-EQUIV="expires" CONTENT="0">
匹配中文字符:[\u4e00-\u9fa5] 匹配雙字節字符(含漢字):[^\x00-\xff] 匹配空行:\n[\s| ]*\r 匹配 HTML 標記:/<(.*)>.*<\/\1>|<(.*) \/>/ 匹配首尾空格:(^\s*)|(\s*$) 匹配 Email:\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)* 匹配 URL:https://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?
用正則限制輸入框內容的例子:
只能輸入中文:onkeyup="value=value.replace(/[^\u4E00-\u9FA5]/g,'')" onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\u4E00-\u9FA5]/g,''))"
只能輸入全角:onkeyup="value=value.replace(/[^\uFF00-\uFFFF]/g,'')"
只能輸入數字:onkeyup="value=value.replace(/[^\d]/g,'')"
只能輸入數字和英文:onkeyup="value=value.replace(/[\W]/g,'')"
<IMG SRC="mypicture.jpg" HEIGHT="100px" WIDTH="100px" GALLERYIMG="false"> <meta http-equiv="imagetoolbar" content="no">
function getoffset(e) {
var t = e.offsetTop, l = e.offsetLeft;
while (e = e.offsetParent) { t += e.offsetTop; l += e.offsetLeft; }
return [t, l];
}
// 也可以用:
oRect = obj.getBoundingClientRect();
oRect.left; oRect.top;
function cc() {
var e = event.srcElement;
var r = e.createTextRange();
r.moveStart('character', e.value.length);
r.collapse(true);
r.select();
}
<input type=text name=text1 value="123" onfocus="cc()">
進入頁面:<meta http-equiv="Page-Enter" content="revealTrans(duration=x, transition=y)"> 退出頁面:<meta http-equiv="Page-Exit" content="revealTrans(duration=x, transition=y)">
duration 是特效持續時間(秒),transition 取值 1-23:0 矩形縮小、1 矩形擴大、2 圓形縮小、3 圓形擴大、4 下到上刷新、5 上到下刷新、6 左到右刷新、7 右到左刷新、8 豎百葉窗、9 橫百葉窗、10 錯位橫百葉窗、11 錯位豎百葉窗、12 點擴散、13 左右到中間刷新、14 中間到左右刷新、15 中間到上下、16 上下到中間、17 右下到左上、18 右上到左下、19 左上到右下、20 左下到右上、21 橫條、22 豎條。
<meta name="ROBOTS" content="屬性值">
屬性值含義:all(檢索且查詢頁上鏈接)、none(不檢索也不查詢鏈接)、index(檢索)、follow(查詢頁上鏈接)、noindex(不檢索但可查詢鏈接)、nofollow(不查詢鏈接)。
<p style="page-break-after:always">page1</p> <p style="page-break-after:always">page2</p>
<style media=print>
.Noprint{display:none;} /* 打印時隱藏非打印項目 */
.PageNext{page-break-after:always;} /* 控制分頁 */
</style>
<object id="WebBrowser" width=0 height=0 classid="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></object>
<input type=button value=打印 onclick=document.all.WebBrowser.ExecWB(6,1)>
<input type=button value=直接打印 onclick=document.all.WebBrowser.ExecWB(6,6)>
<input type=button value=頁面設置 onclick=document.all.WebBrowser.ExecWB(8,1)>
<input type=button value=打印預覽 onclick=document.all.WebBrowser.ExecWB(7,1)>
ExecWB 常用指令:1 打開、2 關閉所有窗口並開新窗口、4 保存網頁、6 打印、7 打印預覽、8 頁面設置、10 查看頁面屬性、17 全選、22 刷新、45 無提示關閉窗體。
function checkBrowser() {
this.ver = navigator.appVersion;
this.dom = document.getElementById ? 1 : 0;
this.ie6 = (this.ver.indexOf("MSIE 6") > -1 && this.dom) ? 1 : 0;
this.ie5 = (this.ver.indexOf("MSIE 5") > -1 && this.dom) ? 1 : 0;
this.ie4 = (document.all && !this.dom) ? 1 : 0;
this.ns5 = (this.dom && parseInt(this.ver) >= 5) ? 1 : 0;
this.ns4 = (document.layers && !this.dom) ? 1 : 0;
this.mac = (this.ver.indexOf('Mac') > -1) ? 1 : 0;
this.ope = (navigator.userAgent.indexOf('Opera') > -1);
this.ie = (this.ie6 || this.ie5 || this.ie4);
this.ns = (this.ns4 || this.ns5);
this.bw = (this.ie6 || this.ie5 || this.ie4 || this.ns5 || this.ns4 || this.mac || this.ope);
this.nbw = (!this.bw);
return this;
}
var Obj;
function MouseDown(obj) {
Obj = obj;
Obj.setCapture();
Obj.l = event.x - Obj.style.pixelLeft;
Obj.t = event.y - Obj.style.pixelTop;
}
function MouseMove() {
if (Obj != null) {
Obj.style.left = event.x - Obj.l;
Obj.style.top = event.y - Obj.t;
}
}
function MouseUp() {
if (Obj != null) { Obj.releaseCapture(); Obj = null; }
}
var doc = window.frames["f"].document;
function s(){
if (doc.readyState == "complete") {
document.all.f.style.height = doc.body.scrollHeight;
document.all.f.style.width = doc.body.scrollWidth;
}
}
doc.onreadystatechange = s;
<HTML><HEAD>
<META NAME="save" CONTENT="history">
<STYLE>.sHistory {behavior:url(#default#savehistory);}</STYLE>
</HEAD><BODY>
<INPUT class="sHistory" type=text id=oPersistInput>
</BODY></HTML>
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;";
}
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(fRef, mDelay);
};
function test(x){ alert(x); }
window.setTimeout(test, 1000, 'fason');
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);
};
readyState 是 xmlhttp 返回數據的進度:0 = 載入中,1 = 未初始化,2 = 已載入,3 = 運行中,4 = 完成。
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;
}
原理是用一個絕對定位的浮層跟著鼠標走,並通過 filter 的 Alpha 做淡入淡出:
<a href="#" title="這是提示">tip</a>
<script Language="JavaScript">
tPopWait = 50; // 停留 50 毫秒後顯示提示
tPopShow = 5000; // 顯示 5000 毫秒後關閉提示
showPopStep = 20;
popOpacity = 99;
var sPop = null, curShow = null, tFadeOut = null, tFadeIn = null, tFadeWaiting = null;
document.write("<style type='text/css' id='defaultPopStyle'>");
document.write(".cPopText { background-color: #F8F8F5; color:#000000; border: 1px #000000 solid; font-size: 12px; padding: 2px 4px; height: 20px; filter: Alpha(Opacity=0)}");
document.write("</style>");
document.write("<div id='dypopLayer' style='position:absolute;z-index:1000;' class='cPopText'></div>");
function showPopupText(){
var o = event.srcElement;
MouseX = event.x; MouseY = event.y;
if (o.alt != null && o.alt != "") { o.dypop = o.alt; o.alt = ""; }
if (o.title != null && o.title != "") { o.dypop = o.title; o.title = ""; }
if (o.dypop != sPop) {
sPop = o.dypop;
clearTimeout(curShow); clearTimeout(tFadeOut); clearTimeout(tFadeIn); clearTimeout(tFadeWaiting);
if (sPop == null || sPop == "") {
dypopLayer.innerHTML = "";
dypopLayer.style.filter = "Alpha()";
dypopLayer.filters.Alpha.opacity = 0;
} else {
popStyle = (o.dyclass != null) ? o.dyclass : "cPopText";
curShow = setTimeout("showIt()", tPopWait);
}
}
}
function showIt(){
dypopLayer.className = popStyle;
dypopLayer.innerHTML = sPop;
popWidth = dypopLayer.clientWidth;
popHeight = dypopLayer.clientHeight;
if (MouseX + 12 + popWidth > document.body.clientWidth) popLeftAdjust = -popWidth - 24; else popLeftAdjust = 0;
if (MouseY + 12 + popHeight > document.body.clientHeight) popTopAdjust = -popHeight - 24; else popTopAdjust = 0;
dypopLayer.style.left = MouseX + 12 + document.body.scrollLeft + popLeftAdjust;
dypopLayer.style.top = MouseY + 12 + document.body.scrollTop + popTopAdjust;
dypopLayer.style.filter = "Alpha(Opacity=0)";
fadeOut();
}
function fadeOut(){
if (dypopLayer.filters.Alpha.opacity < popOpacity) {
dypopLayer.filters.Alpha.opacity += showPopStep;
tFadeOut = setTimeout("fadeOut()", 1);
} else {
dypopLayer.filters.Alpha.opacity = popOpacity;
tFadeWaiting = setTimeout("fadeIn()", tPopShow);
}
}
function fadeIn(){
if (dypopLayer.filters.Alpha.opacity > 0) {
dypopLayer.filters.Alpha.opacity -= 1;
tFadeIn = setTimeout("fadeIn()", 1);
}
}
document.onmouseover = showPopupText;
</script>
var ie = navigator.appName == "Microsoft Internet Explorer" ? true : false;
function keyDown(e) {
if (!ie) {
var nkey = e.which;
var realkey = String.fromCharCode(e.which);
}
if (ie) {
var iekey = event.keyCode;
var realkey = String.fromCharCode(event.keyCode);
if (event.keyCode == 32) realkey = '空格';
if (event.keyCode == 13) realkey = '回車';
if (event.keyCode == 27) realkey = 'Esc';
if (event.keyCode == 16) realkey = 'Shift';
if (event.keyCode == 17) realkey = 'Ctrl';
if (event.keyCode == 18) realkey = 'Alt';
}
alert('ns 鍵值: ' + nkey + '\n' + 'ie 鍵值: ' + iekey + '\n' + '實際鍵為 ' + realkey);
}
document.onkeydown = keyDown;
var flag = false;
function DrawImage(ImgD){
var image = new Image();
var iwidth = 80; // 允許的最大寬度
var 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;
}
ImgD.alt = image.width + "×" + 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)">
function Import() {
for (var i = 0; i < arguments.length; i++) {
var file = arguments[i];
if (file.match(/\.js$/i))
document.write('<script type="text/javascript" src="' + file + '"></sc' + 'ript>');
else
document.write('<style type="text/css">@import "' + file + '" ;</style>');
}
}
mergeAttributes 可以把所有讀寫標簽屬性復制到指定元素:
function fnMerge(){
oSource.children[1].mergeAttributes(oSource.children[0]);
}
function document.oncontextmenu(){ event.returnValue = false; } // 屏蔽右鍵
function window.onhelp(){ return false; } // 屏蔽 F1 幫助
document.onkeydown = function() {
// 屏蔽退格、F5、Ctrl+R
if ((event.keyCode == 8) || (event.keyCode == 116) || (event.ctrlKey && event.keyCode == 82)) {
event.keyCode = 0;
event.returnValue = false;
}
if (event.keyCode == 122) { event.keyCode = 0; event.returnValue = false; } // F11
if (event.ctrlKey && event.keyCode == 78) event.returnValue = false; // Ctrl+N
if (event.shiftKey && event.keyCode == 121) event.returnValue = false; // Shift+F10
};
@media print { * {display:none} }
以上都是些零散但實用的小累積,希望對你有幫助。