這裡彙整了幾個常見又實用的小技巧,涵蓋禁用右鍵、字體縮放、連結新視窗開啟、樣式表切換、回到頂部、取得滑鼠座標與圖片預載入等,都是實際專案裡經常派上用場的片段。
$(document).ready(function() {
$(document).bind("contextmenu", function(e) {
alert("No right-clicking!"); // 提示訊息,可省略
return false; // 取消預設選單
});
});
$(document).ready(function() {
var originalFontSize = $('html').css('font-size');
$(".increaseFont").click(function() {
var currentFontSize = parseFloat($('html').css('font-size'), 10);
$('html').css('font-size', currentFontSize*1.2);
return false;
});
$(".decreaseFont").click(function() {
var currentFontSize = parseFloat($('html').css('font-size'), 10);
$('html').css('font-size', currentFontSize*0.8);
return false;
});
$(".resetFont").click(function(){
$('html').css('font-size', originalFontSize);
});
});
$(document).ready(function() {
$("a[href^='http']").attr('target', '_blank');
});
$(document).ready(function() {
$("a.cssSwap").click(function() {
$('link[rel=stylesheet]').attr('href', $(this).attr('rel'));
});
});
$(document).ready(function() {
$('#top').click(function() {
$(document).scrollTo(0, 500);
});
});
$().mousemove(function(e){
$('p').html("X Axis : " + e.pageX + " | Y Axis " + e.pageY);
});
jQuery.preloadImagesInWebPage = function() {
for(var ctr = 0; ctr < arguments.length; ctr++){
jQuery("").attr("src", arguments[ctr]);
}
}
// 呼叫方式
$.preloadImages("image1.gif", "image2.gif", "image3.gif");
判斷圖片是否載入完成:
$('#imageObject').attr('src', 'image1.gif').load(function() {
alert('The image has been loaded…');
});
這些片段看似零散,卻能覆蓋日常介面互動的大部分小需求,收錄起來能省下不少重複查資料的時間。