jQuery 曾是前端最普及的函式庫,即使到今天,維護老專案時還是躲不掉。以下七個片段都是實用度很高的小工具,值得收進你的工具箱。
$(document).ready(function () {
// 選出所有 href 以 http 開頭的錨點,加上 target="_blank"
$("a[href^='http']").attr('target', '_blank');
});
[href^='http'] 是「前方比對」選擇器,只抓絕對路徑的外部連結,站內相對路徑不受影響。提醒一下,使用 target="_blank" 時請同時加上 rel="noopener noreferrer",避免新頁面透過 window.opener 操作你的頁面。
// 記錄最高值
var maxHeight = 0;
function equalHeight(col) {
var $col = $(col);
$col.each(function () {
if ($(this).height() > maxHeight) {
maxHeight = $(this).height();
}
});
$col.height(maxHeight);
}
$(document).ready(function () { equalHeight('.equalHeight'); });
原理是兩趟:先掃過找出最大值,再統一設定。注意 maxHeight 若宣告在全域且函式可能被呼叫多次,記得在函式開頭重設為 0,否則只會越長越大。現代做法用 CSS Grid 或 Flexbox 的 align-items: stretch 一行就能解決,不必寫 JavaScript。
jQuery.preloadImagesInWebPage = function () {
for (var ctr = 0; ctr < arguments.length; ctr++) {
jQuery("<img>").attr("src", arguments[ctr]);
}
};
// 使用
$.preloadImagesInWebPage("image1.gif", "image2.gif", "image3.gif");
// 確認是否載入完成
$('#imageObject').attr('src', 'image1.gif').load(function () {
alert('圖片已載入');
});
技巧是建立 Image 物件並指定 src,瀏覽器就會把它放進快取,之後真正顯示時不必再等網路。
$(document).ready(function () {
$(document).bind("contextmenu", function (e) {
return false; // 取消預設的內容選單
});
});
誠實說:這招只能阻擋最不用功的取用者,任何人都能用 DevTools 或選單列繞過,而且會妨礙正常使用者的操作習慣(例如叫出拼字檢查)。我通常不建議這麼做,除非有明確的業務理由。
$(document).ready(function () {
window.setTimeout(function () {
// 500 毫秒後執行
}, 500);
});
延遲執行 DOM 操作時,記得放在 ready 裡或在回呼中再次確認元素存在。
<div id="foo">
<div id="bar"></div>
<div id="baz">
<div id="biz"></div>
<span><span></span></span>
</div>
</div>
<script type="text/javascript">
// 只算 foo 的直接子 div(不含 baz 內部的 biz)
alert($("#foo > div").size());
</script>
> 是「直接子代」選擇器,不會往下鑽。這與後代選擇器 $("#foo div") 有本質差異。順帶一提,.size() 已被標示為 deprecated,改用 .length 即可,效能還更好。
jQuery.fn.center = function () {
this.css("position", "absolute");
this.css("top", ($(window).height() - this.height()) / 2 + $(window).scrollTop() + "px");
this.css("left", ($(window).width() - this.width()) / 2 + $(window).scrollLeft() + "px");
return this;
};
// 使用
$('#foo').center();
這個片段正好示範了上一篇提到的重點:必須加上 scrollTop 與 scrollLeft。少了它們,當使用者捲動過後,「置中」的元素會跑到視窗外面。最後 return this 也不能省,它讓這個方法可以繼續串鏈。
若只是要置中,現代 CSS 一行就夠:display: grid; place-items: center; 或 position: fixed; inset: 0; margin: auto;。