萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML 腳本教學

前端開發常用 HTML/JS 代碼片段速查手冊

開發過程中,總有一些「用得到但記不住」的小技巧。本文整理了頁面緩存控制、iframe 交互、滾動條定製、光標樣式、表單郵件提交、伺服器變數獲取、文字豎排、收藏夾圖標等高頻代碼片段,供快速查閱。

1. 頁面緩存控制(放入 <head>)

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="Cache-Control" content="no-cache,must-revalidate">
<meta http-equiv="expires" content="Wed, 26 Feb 1978 08:21:57 GMT">

jQuery AJAX 全域禁用緩存:

$.ajaxSetup({ cache: false });

2. 表單郵件直接提交

<form name="form1" method="post" action="mailto:****@***.com" enctype="text/plain">
  <input type="submit">
</form>

3. iframe 父子頁面交互

  • 子頁面刷新父頁面:window.opener.location.reload()
  • 父頁面調用子頁面函數:document.getElementById('iframeId').contentWindow.fn()
  • 子頁面調用父頁面函數:window.parent.fn()

4. 視窗尺寸與滾動條控制

<!-- 指定開窗尺寸 -->
<body onload="top.resizeTo(300,200);">

<!-- 隱藏垂直滾動條 -->
<body style="overflow-y:hidden">

<!-- 隱藏水平滾動條 -->
<body style="overflow-x:hidden">

<!-- 完全隱藏滾動條 -->
<body scroll="no"> 或 <body style="overflow:hidden">

5. 圖片鏈接去虛線框

<a href="#" onfocus="this.blur()"><img src="logo.jpg" border="0"></a>

6. 背景圖片固定不隨頁面滾動

<style>
body {
  background-image: url(logo.gif);
  background-repeat: no-repeat;
  background-position: center;
  background-attachment: fixed; /* 關鍵屬性 */
}
</style>

7. CSS 光標樣式速查表

值效果
auto瀏覽器預設
default標準箭頭
pointer / hand手形(可點擊)
wait等待(沙漏/圈圈)
textI 形(文字輸入)
move移動十字箭頭
not-allowed禁止(斜線圓圈)
help問號
e-resize, n-resize, ne-resize...各方向縮放

8. 伺服器端變數獲取

<!-- 客戶端 IP -->
<%= Request.ServerVariables("HTTP_X_FORWARDED_FOR") %>
<!-- 若為空則用 REMOTE_ADDR -->

<!-- 伺服器資訊 -->
伺服器名稱: <%= Request.ServerVariables("SERVER_NAME") %>
伺服器 IP: <%= Request.ServerVariables("LOCAL_ADDR") %>
伺服器埠: <%= Request.ServerVariables("SERVER_PORT") %>
伺服器時間: <%= now %>
IIS 版本: <%= Request.ServerVariables("SERVER_SOFTWARE") %>
腳本超時: <%= Server.ScriptTimeout %>
文件物理路徑: <%= Server.MapPath(Request.ServerVariables("SCRIPT_NAME")) %>
CPU 數量: <%= Request.ServerVariables("NUMBER_OF_PROCESSORS") %>
作業系統: <%= Request.ServerVariables("OS") %>

9. 文字豎向排版

<style>
.shupai { writing-mode: tb-rl; } /* IE 專屬,現代瀏覽器請用 writing-mode: vertical-rl; */
</style>

10. 收藏夾圖標

<link rel="Shortcut Icon" href="favicon.ico">

11. 字符串截斷函數(ASP/VBScript)

Function formatStr(str, len)
  If Len(str) > len Then
    formatStr = Left(str, len) & "..."
  Else
    formatStr = str
  End If
End Function

12. 圖片自適應寬度

<script>
function DrawImage(img) {
  var image = new Image();
  image.src = img.src;
  if (image.width > 0 && image.height > 0) {
    if (image.width > 120) img.width = 120;
    else img.width = image.width;
    img.alt = image.width + "×" + image.height;
  }
}
</script>
<img src="..." onload="DrawImage(this)">

13. 頁面跳轉

<meta http-equiv="refresh" content="0; url=/target-page.html">
提示:部分代碼為經典 ASP / VBScript 語法,現代項目請根據技術棧(PHP、Node.js、ASP.NET Core 等)轉換對應寫法。
copyright © 萬盛學電腦網 all rights reserved