開発で使うかもしれないjQueryのテクニック


1)右クリック禁止Webアプリケーションを開発する時、右クリック機能を無効にする必要がある場合があります。このコードを使って、jQuery開発者はウェブページでマウスの右クリックを無効にします。コードは以下の通りです。
 
$(document).ready(function() {
//catch the right-click context menu
$(document).bind("contextmenu",function(e) {
//warning prompt - optional
alert("No right-clicking!");

//delete the default context menu
return false;
});
});
2)テキストのスケーリングには下記のコードが使われています。ユーザーはウェブページのフォントサイズを大きくしたり、スケーリングしたりする必要があります。コードは以下の通りです。
 
$(document).ready(function() {
//find the current font size
var originalFontSize = $('html').css('font-size');

//Increase the text size
$(".increaseFont").click(function() {
var currentFontSize = $('html').css('font-size');
var currentFontSizeNumber = parseFloat(currentFontSize, 10);

var newFontSize = currentFontSizeNumber*1.2;
$('html').css('font-size', newFontSize);
return false;
});

//Decrease the Text Size
$(".decreaseFont").click(function() {
var currentFontSize = $('html').css('font-size');
var currentFontSizeNum = parseFloat(currentFontSize, 10);

var newFontSize = currentFontSizeNum*0.8;
$('html').css('font-size', newFontSize);
return false;
});

// Reset Font Size
$(".resetFont").click(function(){
$('html').css('font-size', originalFontSize);
});
});
4)スタイルシートの切り替えは、サイトの肌替えはどうやってするか分かりますか?下のコードはスタイルシートの切替機能を実現するのに役立ちます。下の通りです。
 
$(document).ready(function() {
//select all anchor tags that have http in the href
//and apply the target=_blank
$("a[href^='http']").attr('target','_blank');
});
)トップに戻ります。これは現在のウェブサイトでよく使われているバックトップ機能です。特にページが長い場合に適しています。コードは簡単で、以下の通りです。
 
$(document).ready(function() {
$("a.cssSwap").click(function() {
//swap the link rel attribute with the value in the rel
$('link[rel=stylesheet]').attr('href' , $(this).attr('rel'));
});
});
6)マウスのX、Y座標の下のコードを取得すると、マウスのX、Y座標を取得できます。コードは以下の通りです。
 
$(document).ready(function() {
//when the id="top" link is clicked
$('#top').click(function() {
//scoll the page back to the top
$(document).scrollTo(0,500);
}
});
8)このピクチャのプリロードフラグメントは、ピクチャを高速で事前にロードすることができます。待つ必要はありません。コードは以下の通りです。
 
$().mousemove(function(e){
//display the x and y axis values inside the P element
$('p').html("X Axis : " + e.pageX + " | Y Axis " + e.pageY);
});
呼び出し方法:
 
$(document).ready(function() {
$().mousemove(function(e){
$('# MouseCoordinates ').html("X Axis Position = " + e.pageX + " and Y Axis Position = " + e.pageY);
});