這份整理收錄了大量可直接複製使用的前端小技巧,涵蓋輸入框、按鈕外觀、視窗控制、事件處理、表格操作與繪圖等主題。以下依用途重新分類,並保留最具代表性的程式碼。
onBlur:失去輸入焦點後觸發。onFocus:獲得焦點時觸發。onChange:文字值改變時觸發。onSelect:文字被選取(highlight)時觸發。經典的「提示文字」做法——點擊時文字消失,離開時若為空則還原:
<input type="text" value="郭強"
onfocus="if(value=='郭強'){value=''}"
onblur="if(value==''){value='郭強'}">
線條型輸入框(只留底線)與平面輸入框:
<input type="text" name="T1" size="20"
style="border-style: solid; border-width: 1">
<input name="Password" size="10" type="password"
style="border-left-width:0; border-right-width:0; border-top-width:0;
border-bottom-style:solid; border-bottom-width:1;
background-color:#9CEB9C">
改變文字框背景色,可用 CSS class 搭配圖片:
.input2 { background-image: url('../images/inputbg.gif'); font-size: 12px; }
<input name="content" type="text" size="47" class="input2" maxlength="50">
停用輸入法(IME):<input style="ime-mode: disabled">;關閉自動完成:<input type="text" autocomplete="off">。
用 label 讓點擊文字也能選取單選鈕:
<input type="radio" name="regtype" value="A03" id="A03"> <label for="A03">情侶:一次註冊兩個帳戶</label>
下拉選單滑過即全部展開:
<select onmouseover="this.size=this.length" onmouseout="this.size=1"> ... </select>
點選非空值才跳轉:
<select onchange='if(this.value!="")window.open(this.value)'> <option selected>主辦單位</option> <option value="https://www.bjd.com.cn/">北京日報</option> </select>
滑鼠移入移出改顏色:
<input type="submit" value="找吧" name="B1" class="button"
onMouseOut="this.style.color='blue'"
onMouseOver="this.style.color='red'">
平面按鈕與自訂背景色:
<input type="submit" value="訂閱"
style="border:1px solid #666666; height:17px; width:25pt;
font-size:9pt; background-color:#E8E8FF; color:#666666">
用切換 class 的方式換按鈕樣式或背景圖:
.style3 { background: url(image/buttonbg1.gif); width: 60px; height: 22px; }
.style4 { background: url(image/buttonbg2.gif); font-weight: bold; }
<input type="submit" value="提 交" class="style3"
onmouseover="this.className='style4'"
onmouseout="this.className='style3'">
透明背景的按鈕:style="background-color: transparent; border: 0;";滑過時游標變等待:onclick="this.style.cursor='wait'"。
改水平線樣式:<hr size="0" noshade color="#C0C0C0">。
改變表格儲存格背景:
<td onmouseover="this.bgColor='#FFFFFF'" onmouseout="this.bgColor='#FAFBFC'">
window.resizeTo(300,283)。window.history.back()、window.history.forward()、document.location.reload()。document.location = "https://..." 或 document.location.assign("...");不可返回的跳轉用 location.replace('...')。document.location.href = "目標文件"。window.blur()。document.URL。setTimeout("change_color()", 600)。setTimeout("self.close()", 10000)。window.external.AddFavorite(url, title)。navigator.cookieEnabled。screen.width、screen.height。雙擊自動滾屏:
var currentpos, timer;
function initialize() { timer = setInterval("scrollwindow()", 1); }
function sc() { clearInterval(timer); }
function scrollwindow() {
currentpos = document.body.scrollTop;
window.scroll(0, ++currentpos);
if (currentpos != document.body.scrollTop) { sc(); }
}
document.onmousedown = sc;
document.ondblclick = initialize;
網頁上顯示即時時鐘:
var clock_id;
window.onload = function() {
clock_id = setInterval("document.form1.txtclock.value = (new Date);", 1000);
}
<a href="" onMouseOver="hello()">link</a>。if (event.button == 1) { /* 左鍵 */ }。if (event.ctrlKey && window.event.keyCode == 13)。
document.onkeydown = function() {
if (event.ctrlKey && event.keyCode == 81) { alert(1); }
}
if (event.keyCode == 13) event.keyCode = 9;event.altKey、event.ctrlKey、event.shiftKey。event.type、event.srcElement、event.srcElement.tagName。event.cancelBubble = true。oncontextmenu="event.returnValue = false"。
function noEffect() {
with (event) { returnValue = false; cancelBubble = true; }
return;
}
<body onselectstart="noEffect()" oncontextmenu="noEffect()">
滑鼠座標的四個屬性差異值得記牢:event.x 相對於目標事件的父元素外邊界;clientX 相對於客戶區(不含捲軸);offsetX 相對於父元素內邊界;screenX 相對於整個螢幕。
取得目前點擊所在列的行號:
function getrow(obj) {
if (event.srcElement.tagName == "TD") {
curRow = event.srcElement.parentElement;
alert("這是第" + (curRow.rowIndex + 1) + "行");
}
}
刪除某列(索引從 0 起):document.all.myTable.deleteRow(xx)。
動態新增一列並插入輸入框:
function add() {
t1.insertRow().insertCell().innerHTML = '<input name="test' + t1.rows.length + '">';
}
寫入指定儲存格:tbl.rows[0].cells[1].innerText = document.form.text1.value;
節點操作:交換 c1.swapNode(c2)、刪除 trall.removeNode(c2)、新增 addNode();取得父子標籤 event.srcElement.children[0] 與 event.srcElement.parentElement。
控制某個元件的顯示:document.all.item('Layer2').style.display = "block"(設為 "none" 即隱藏)。
改變字級:
function doZoom(size) {
document.getElementById('zoom').style.fontSize = size + 'px';
}
使文字上下滾動,滑過即暫停:
<marquee direction="up" scrollamount="1" scrolldelay="100"
onmouseover="this.stop()" onmouseout="this.start()" height="60">
內容放在這裡
</marquee>
雙線游標連結:
A:hover { text-decoration: underline overline; color: #FF0000; }
在 div 中直接寫入 HTML:
<input type="button" onclick="a1.innerHTML='<font color=red>*</font>'"> <div id="a1"></div>
頁面翻轉(由右至左):<html dir="rtl">。
window.clipboardData.setData('text', document.selection.createRange().text)。
function JM_cc(bb) {
var ob = eval("document.form1." + bb);
ob.select();
js = ob.createTextRange();
js.execCommand("Copy");
}
document.selection.createRange().text。
function Exists(filespec) {
if (filespec) {
var fso = new ActiveXObject("Scripting.FileSystemObject");
alert(fso.FileExists(filespec));
}
}
fso.GetFile("路徑").DateLastModified。new ActiveXObject("WScript.Network") 可取 UserDomain、ComputerName、UserName。document.all,寫成 document.all ? 1 : 0。navigator.appName 比較 "Microsoft Internet Explorer" 或 "Netscape"。document.write(navigator.userAgent)。動態改變按鈕的 disabled 狀態:
function haha() {
for (var i = 0; i < document.form1.elements.length; i++) {
if (document.form1.elements[i].name.indexOf("bb") != -1) {
document.form1.elements[i].disabled = !document.form1.elements[i].disabled;
}
}
}
關閉視窗前提醒(IE):
function verifyClose() {
event.returnValue = "we really like you and hope you will stay longer.";
}
window.onbeforeunload = verifyClose;
if (!('0' <= char && char <= '9'));字元轉數字:parseInt(char)。alert(a.toFixed(2))。
function format_number(str, digit) {
if (isNaN(str)) { alert("您傳入的值不是數字!"); return 0; }
else if (Math.round(digit) != digit) { alert("小數位數不是整數!"); return 0; }
else return Math.round(parseFloat(str) * Math.pow(10, digit)) / Math.pow(10, digit);
}
tDate = new Date(2004, 1, 8, 14, 35); // 年, 月, 日, 時, 分
dDate = new Date();
tDate < dDate ? alert("早於") : alert("晚於");
注意月份從 0 起算。
document.write(document.lastModified)。柱狀圖的基本寫法是用 v:rect 畫長條,高度依比例換算:
<style>
v\:* { behavior: url(#default#VML); }
</style>
<v:rect fillcolor='red' style='width:20;height:200'>
<br>%12<br>4人
<v:Extrusion backdepth='15pt' on='true'/>
</v:rect>
圓餅圖則用 v:group 包多個 v:shape,透過 v:path 的 ae(arc-to)指令描述扇區,滑鼠移入時加粗邊框並在圖例區顯示說明:
function show(pie) {
pie.strokecolor = pie.fillcolor;
pie.strokeweight = 10;
div1.innerHTML = "<font size=2 color=red> " + pie.id + "</font> " + pie.title;
}
function hide(pie) {
pie.strokecolor = "white";
pie.strokeweight = 1;
div1.innerHTML = "";
}
值得補充的是:VML 只存在於舊版 IE,如今應改用 SVG、Canvas,或直接引入 Chart.js、ECharts 這類圖表庫,才能跨瀏覽器呈現。
function hi(str) {
document.write(document.lastModified);
alert("hi " + str + "!");
}
function bgChange(selObj) {
newColor = selObj.options[selObj.selectedIndex].text;
document.bgColor = newColor;
selObj.selectedIndex = -1;
}
newwin = window.open('about:blank', '', 'top=10');
newwin.document.write('內容');
opener.document.form2.text2.value = value2;,父視窗改子視窗 newWin.document.form1.text1.value = value1;。<input type="button" onclick="parent.test();" value="呼叫">。<a href="#1"> 搭配 <a name="1">。<a href="vote.asp?CurPage=8&id=3488">。guoguo.click();。autocomplete="off"。text1.scrollTop = text1.scrollHeight。document.execCommand('print', ...)、'saveas'、'undo'、'CreateLink'。MsgBox "確定刪除嗎?", 4。這批技巧多數寫於 IE 獨大的年代,其中 document.all、VML、showModalDialog、execCommand、ActiveXObject 等在現代瀏覽器中已不受支援或不建議使用。學習時重點應放在「事件模型、DOM 操作、座標計算」這些觀念上,實作時改用標準 API:document.querySelector、addEventListener、fetch、canvas/svg,並以 navigator.clipboard 取代剪貼板 hack。