本文我们将为jQuery用户分享8个超实用的技巧攻略。jQuery是JavaScript最好的库之一,主要用于制作动画、事件处理,支持Ajax及HTML 脚本客户端。此外,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;
});
});
使用这段代码,用户可根据需求重新设定文本尺寸(增加或减少)。
$(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);
});
});
使用这段代码会帮助用户在新窗口打开链接,为用户带来更好的用户体验。
$(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'));
});
});
此代码对于长时间点击单页面非常实用,你可以在重要关头点击“返回顶部”功能。
$(document).ready(function() { //when the id="top" link is clicked
$('#top').click(function() { //scoll the page back to the top
$(document).scrollTo(0,500);
}
});
平滑滚动到锚点
// HTML:
//</pre> <h1 id="anchor">Lorem Ipsum</h1> <pre>
// <a class="topLink" href="#anchor">Back to Top</a>
$(document).ready(function() {
$("a.topLink").click(function() {
$("html, body").animate(
{scrollTop: $($(this).attr("href")).offset().top + "px" },
{ duration: 500, easing: "swing" }
);
return false;
});
});
6)获取鼠标指针的X / Y轴
$().mousemove(function(e){ //display the x and y axis values inside the P element
$('p').html("X Axis : " + e.pageX + " | Y Axis " + e.pageY);
});
7)检测当前鼠标坐标
使用这个脚本,你可以在任何网络浏览器获取鼠标坐标。
$(document).ready(function() {
$().mousemove(function(e) {
$('# MouseCoordinates ').html("X Axis Position = " + e.pageX + " and Y Axis Position = " + e.pageY);
});
});
8)缩放图片
虽然图片应该在服务器端缩放,不过如果服务器端未做缩放,需要再客户端缩放的时候,可以使用下面这个方便的代码片段:
$(window).bind("load", function() { // IMAGE RESIZE
$('#product_cat_list img').each(function() {
var maxWidth = 120;
var maxHeight = 120;
var ratio = 0;
var width = $(this).width();
var height = $(this).height();
if(width > maxWidth){
ratio = maxWidth / width;
$(this).css("width", maxWidth);
$(this).css("height", height * ratio);
height = height * ratio;
}
var width = $(this).width();
var height = $(this).height();
if(height > maxHeight){
ratio = maxHeight / height;
$(this).css("height", maxHeight);
$(this).css("width", width * ratio);
width = width * ratio;
}
}); //$("#contentpage img").show(); // IMAGE RESIZE
});
很多网站使用了流行的瀑布图布局,这种类型的网站在页面滚动的时候会自动加载内容。下面这段代码让你能够把这个功能搬到你的网站上。
var loading = false;
$(window).scroll(function(){
if((($(window).scrollTop()+$(window).height())+250)>=$(document).height()){
if(loading == false){
loading = true;
$('#loadingbar').css("display","block");
$.get("load.php?start="+$('#loaded_max').val(), function(loaded){
$('body').append(loaded);
$('#loaded_max').val(parseInt($('#loaded_max').val())+50);
$('#loadingbar').css("display","none"); loading = false;
});
}
}
});
$(document).ready(function() {
$('#loaded_max').val(50);
});
在表单功能中,经常会有检测用户输入的密码强度的功能,下面这个代码片段使用正则表达式来检测密码是否足够安全,当然记得在服务端也进行表单验证。
$('#pass').keyup(function(e) {
var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\W).*[ ubbcodeplace_4 ]quot;, "g");
var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*[ ubbcodeplace_4 ]quot;, "g");
var enoughRegex = new RegExp("(?=.{6,}).*", "g");
if (false == enoughRegex.test($(this).val())) {
$('#passstrength').html('More Characters');
} else if (strongRegex.test($(this).val())) {
$('#passstrength').className = 'ok';
$('#passstrength').html('Strong!');
} else if (mediumRegex.test($(this).val())) {
$('#passstrength').className = 'alert';
$('#passstrength').html('Medium!');
} else {
$('#passstrength').className = 'error';
$('#passstrength').html('Weak!');
}
return true;
});
使用纯 CSS代码实现均衡元素的高度比较困难,而下面这段 jQuery 代码会根据最高的元素来均衡所有的 Div 元素。
var maxHeight = 0;
$("div").each(function(){
if ($(this).height() > maxHeight) {
maxHeight = $(this).height();
}
});
$("div").height(maxHeight);
至今,IE6 在国内仍然占据了大量的份额,因此在 Web 开发中仍然需要考虑 IE6 的兼容问题。比较常用的 IE6 PNG 图片问题,下面这段代码可以方便的修复。
$('.pngfix').each( function() {
$(this).attr('writing-mode', 'tb-rl');
$(this).css('background-image', 'none');
$(this).css( 'filter', 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="path/to/image.png",sizingMethod="scale")');
});
使用 jQuery 解析 JSON 数据并不复杂。下面是一个高效解析 JSON 数据并将其追加到您的网页的例子。
function parseJson(){
$.getJSON('hcj.json',getPosts);
function getPosts(data){
for(var i = 0; i < 5; i++){
var strPost = '<h2>' + data.posts[i].title + '</h2>' + '<p>' + data.posts[i].excerpt + '</p>' + '<a href="' + data.posts[i].url + '" title="Read ' + data.posts[i].title + '">Read ></a>';
$('body').append(strPost);
}
}
}
$(document).ready(function(){
parseJson();
});
这是一个很老的功能了,在大的列表或表格中,隔行颜色可以大大提高内容的可读性。下面的代码可以非常简单实现这个功能。
$('div:odd').css("background-color", "#F4F4F8"); $('div:even').css("background-color", "#EFF1F1");
你是否注意到 facebook 相册的图片加载速度特别快?那是因为在你看到这些图片之前已经预加载到你的浏览器缓存中了。下面是实现这个类似功能的代码示例:
var nextimage = "/images/some-image.jpg";
$(document).ready(function(){
window.setTimeout(function(){
var img = $("<img>").attr("src", nextimage).load(function(){
});
},
100);
});
这是实现链接的父 Div 也能够点击的简单方法,HTML 示例代码如下:
<div class="myBox"> blah blah blah. <a href="http://google.com">link</a> </div>
下面的 jQuery 代码让整个 Div 可点击:
$(".myBox").click(function(){ window.location=$(this).find("a").attr("href"); return false; });