這份清單涵蓋日常開發最常遇到的小需求:禁止右鍵選單、搜尋框提示文字、外部連結新窗開啟、瀏覽器偵測、圖片預載、樣式主題切換、欄位等高、動態調整字級、滑鼠座標、元素替換、延遲載入、無衝突模式等等。
$(document).ready(function () {
$(document).bind("contextmenu", function (e) {
return false;
});
});
$(document).ready(function () {
$("input.text1").val("Enter your search text here");
textFill($('input.text1'));
});
function textFill(input) {
var originalvalue = input.val();
input.focus(function () {
if ($.trim(input.val()) == originalvalue) { input.val(''); }
});
input.blur(function () {
if ($.trim(input.val()) == '') { input.val(originalvalue); }
});
}
$(document).ready(function () {
// 例一:所有 http 開頭的連結都開新視窗
$('a[href^="https://"]').attr("target", "_blank");
// 例二:只有帶 rel="external" 的才開新視窗
$('a[@rel$='external']').click(function () {
this.target = "_blank";
});
});
// 用法
// <A href="https://www.opensourcehunter.com" rel="external">open link</A>
注意:新舊版 jQuery 的屬性選擇器語法不同,1.3 之後 @ 前綴已移除,應寫成 a[rel$='external']。
jQuery 1.4 中 $.support 逐步取代 $.browser,而 1.9 之後 $.browser 已完全移除。
$(document).ready(function () {
if ($.browser.mozilla && $.browser.version >= "1.8") { /* Firefox 2+ */ }
if ($.browser.safari) { /* Safari */ }
if ($.browser.chrome) { /* Chrome */ }
if ($.browser.camino) { /* Camino */ }
if ($.browser.opera) { /* Opera */ }
if ($.browser.msie && $.browser.version <= 6) { /* IE6 及以下 */ }
if ($.browser.msie && $.browser.version > 6) { /* IE7 以上 */ }
});
$(document).ready(function () {
jQuery.preloadImages = function () {
for (var i = 0; i < arguments.length; i++) {
$("<img>").attr("src", arguments[i]);
}
};
// 用法
$.preloadImages("image1.jpg", "image2.jpg");
});
$(document).ready(function () {
$("a.Styleswitcher").click(function () {
// 用連結的 rel 值去換掉 stylesheet 的 href
$('link[rel=stylesheet]').attr('href', $(this).attr('rel'));
});
});
// 頁首
// <LINK href="default.css" type="text/css" rel="stylesheet">
// 切換連結
// <A class="Styleswitcher" href="#" rel="default.css">Default Theme</A>
// <A class="Styleswitcher" href="#" rel="red.css">Red Theme</A>
// <A class="Styleswitcher" href="#" rel="blue.css">Blue Theme</A>
$(document).ready(function () {
function equalHeight(group) {
var tallest = 0;
group.each(function () {
var thisHeight = $(this).height();
if (thisHeight > tallest) { tallest = thisHeight; }
});
group.height(tallest);
}
equalHeight($(".left"));
equalHeight($(".right"));
});
實務上更建議用 CSS Flexbox 或 Grid 解決等高問題,JS 方案在字型載入完成後可能還需要重算一次。
$(document).ready(function () {
var originalFontSize = $('html').css('font-size');
$(".resetFont").click(function () {
$('html').css('font-size', originalFontSize);
});
$(".increaseFont").click(function () {
var current = parseFloat($('html').css('font-size'), 10);
$('html').css('font-size', current * 1.2);
return false;
});
$(".decreaseFont").click(function () {
var current = parseFloat($('html').css('font-size'), 10);
$('html').css('font-size', current * 0.8);
return false;
});
});
$(document).ready(function () {
$('a[href*=#]').click(function () {
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
&& location.hostname == this.hostname) {
var $target = $(this.hash);
$target = $target.length && $target || $('[name=' + this.hash.slice(1) + ']');
if ($target.length) {
var targetOffset = $target.offset().top;
$('html,body').animate({ scrollTop: targetOffset }, 900);
return false;
}
}
});
});
// 用法
// <A name="top"></A>
// <A href="#top">go to top</A>
$(document).ready(function () {
$().mousemove(function (e) {
$('#XY').html("X Axis : " + e.pageX + " | Y Axis " + e.pageY);
});
});
// <DIV id="XY"></DIV>
if ($('#id').html()) { /* 有內容 */ }
$('#id').replaceWith('<DIV>I have been replaced</DIV>');
window.setTimeout(function () {
// do something
}, 1000);
var el = $('#id');
el.html(el.html().replace(/word/ig, ""));
if ($('#id').length) { /* 存在 */ }
$("div").click(function () {
window.location = $(this).find("a").attr("href");
return false;
});
// <DIV><A href="index.html">home</A></DIV>
無障礙提醒:這種做法讓鍵盤使用者無法聚焦,比較好的方式是保留 <a> 語意,再用 CSS 把連結的點擊範圍撐滿整個容器。
$(document).ready(function () {
function checkWindowSize() {
if ($(window).width() > 1200) { $('body').addClass('large'); }
else { $('body').removeClass('large'); }
}
$(window).resize(checkWindowSize);
});
var cloned = $('#id').clone();
// <DIV id="id"></DIV>
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;
};
$("#id").center();
$.extend($.expr[':'], {
moreThen1000px: function (a) {
return $(a).width() > 1000;
}
});
$('.box:moreThen1000px').click(function () {
alert('The element that you have clicked is over 1000 pixels wide');
});
$("p").size(); // 亦可寫成 $("p").length
$("ul").addClass("Replaced");
$("ul > li").prepend("‒ ");
/* ul.Replaced { list-style: none; } */
// 例一:透過 jsapi 載入
<SCRIPT src="https://www.google.com/jsapi"></SCRIPT>
<SCRIPT type="text/javascript">
google.load("jquery", "1.2.6");
google.setOnLoadCallback(function () { /* do something */ });
</SCRIPT>
// 例二:直接引用(最快最省事)
<SCRIPT src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"
type="text/javascript"></SCRIPT>
jQuery.fx.off = true;
除錯或做為使用者偏好設定時很好用,也能省下低階裝置的運算資源。
var $jq = jQuery.noConflict();
$jq('#id').show();
先寫好絕對定位在右上角的提示框:
#loading {
position: absolute; z-index: 900; text-align: center;
background-color: #eef2fa; border: 1px solid #d8e3e8;
color: #000; font-size: 12px; padding: 3px; width: 80px;
right: 0; top: 0;
}
再在所有圖片載入完成後把它藏起來:
<script>
jQuery(document).ready(function ($) {
$('img').load(function () {
$('#loading').css("display", "none");
});
});
</script>
<div id="loading">Loading ...</div>
這裡有個常見陷阱:$('img').load() 只對「已經掛上監聽之後才載入」的圖片有效。若圖片在 ready 觸發前就載完了,回呼永遠不會執行,提示框會一直卡在那裡。實務上建議改用 $(window).load() 或在每張圖上檢查 img.complete。