以下八段小程式碼都是早期網頁設計的常見技巧,至今仍可作為語法練習。使用時請注意其中幾項(如 favicon 路徑、addFavorite)依瀏覽器而異,已不建議用於正式專案,但理解原理仍有價值。
用 Date 取得目前小時數,再依區間輸出不同文案:
<script> var text = ""; var day = new Date(); var time = day.getHours(); if (time >= 0 && time < 7) text = "夜貓子,要注意身體哦!"; if (time >= 7 && time < 12) text = "今天的陽光真燦爛啊!"; if (time >= 12 && time < 14) text = "午休時間,保持睡眠哦!"; if (time >= 14 && time < 18) text = "祝您下午工作愉快!"; if (time >= 18 && time <= 22) text = "您又來了,可別聊太久哦!"; if (time >= 22 && time < 24) text = "您應該休息了!"; document.write(text); </script>
實務上請用 document.getElementById('greeting').textContent = text 取代 document.write,後者會在頁面載入後清空整個文件。
<script>
var Windowsheight = 100, Windowswidth = 100, numx = 5;
function openwindow(thelocation) {
var temploc = thelocation;
if (!(window.resizeTo && document.all)
&& !(window.resizeTo && document.getElementById)) {
window.open(thelocation);
return;
}
var windowsize = window.open("", "", "scrollbars");
windowsize.moveTo(0, 0);
windowsize.resizeTo(100, 100);
tenumxt();
}
function tenumxt() {
if (Windowsheight >= screen.availHeight - 3) numx = 0;
windowsize.resizeBy(5, numx);
Windowsheight += 5;
Windowswidth += 5;
if (Windowswidth >= screen.width - 5) {
windowsize.location = temploc;
Windowsheight = 100; Windowswidth = 100; numx = 5;
return;
}
setTimeout(tenumxt, 50);
}
</script>
<a href="javascript:openwindow('https://example.com')">進入</a>
現代瀏覽器基於安全與體驗考量,已大幅限制以腳本控制視窗尺寸與位置,resizeTo/resizeBy 通常只有以 script 開啟的視窗才有效。
製作 16×16 的 ico 檔放在根目錄,於 head 中宣告:
<link rel="shortcut icon" href="favicon.ico" />
<a href="javascript:history.go(-1)">上一頁</a> <a href="javascript:history.go(1)">下一頁</a>
把負號改成正號即為前進,數字代表頁數。
<a href="#" onmouseover="alert('彈出信息!')">顯示的鏈接文字</a>
<script>
if (document.all)
document.body.onmousedown = new Function(
"if (event.button==2||event.button==3)"
+ " window.external.addFavorite('https://example.com','網站名稱')");
</script>
這個寫法只有舊 IE 支援,且 hijack 右鍵鍵的行為在今日屬於反使用者體驗的做法,不建議使用。
<script>
var image = ['tu0.gif', 'tu1.gif', 'tu2.gif', 'tu3.gif', 'tu4.gif'];
var number = Math.floor(Math.random() * image.length);
document.write("<BODY BACKGROUND=" + image[number] + ">");
</script>
更好作法是設定 document.body.style.backgroundImage,並用 CSS 的 background-size 控制縮放。
<head>
<style>
.alpha { filter: Alpha(Opacity=50); opacity: 0.5; }
</style>
</head>
<body>
<table border="1" width="100" height="62" class="alpha" bgcolor="#F2A664">
<tr><td><div align="center">很酷吧!</div></td></tr>
</table>
</body>
filter: Alpha() 是 IE 私有屬性,標準做法是 opacity;兩者並列才能跨瀏覽器。若要讓背景半透明但文字不透明,應改用 rgba() 指定背景色,而非對整個元素設定透明度。