分享10个web前端简单实用的jQuery代码片段

2015年03月26日 11:42 0 点赞 0 评论 更新于 2025-11-21 18:35

尽管各种JavaScript框架和库层出不穷,jQuery仍然是Web前端开发中最常用的工具库。今天,我将向大家分享我认为在网站开发中非常实用的10个简单的jQuery代码片段。

1. 平滑滚动到锚点

在网站底部添加一个让访客快速回到页面顶部的功能是很常见的需求。以下是实现该功能的示例代码:

HTML代码

<h1 id="anchor">Lorem Ipsum</h1>
<p><a href="#anchor" class="topLink">Back to Top</a></p>

jQuery代码

$(document).ready(function() {
$("a.topLink").click(function() {
$("html, body").animate({
scrollTop: $($(this).attr("href")).offset().top + "px"
}, {
duration: 500,
easing: "swing"
});
return false;
});
});

2. 缩放图片

虽然图片应该在服务器端进行缩放,但如果服务器端未做处理,需要在客户端进行缩放时,可以使用下面这个方便的代码片段:

$(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;
}

width = $(this).width();
height = $(this).height();

if (height > maxHeight) {
ratio = maxHeight / height;
$(this).css("height", maxHeight);
$(this).css("width", width * ratio);
width = width * ratio;
}
});
});

3. 滚动时自动加载内容

很多网站采用了流行的瀑布图布局,这种类型的网站在页面滚动时会自动加载内容。下面这段代码可以帮助你在自己的网站上实现该功能:

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);
});

4. 检测密码强度

在表单功能中,经常需要检测用户输入的密码强度。下面这个代码片段使用正则表达式来检测密码是否足够安全,当然,记得在服务端也进行表单验证:

$('#pass').keyup(function(e) {
var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$", "g");
var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
var enoughRegex = new RegExp("(?=.{6,}).*", "g");

if (false == enoughRegex.test($(this).val())) {
$('#passstrength').html('More Characters');
} else if (strongRegex.test($(this).val())) {
$('#passstrength').attr('class', 'ok');
$('#passstrength').html('Strong!');
} else if (mediumRegex.test($(this).val())) {
$('#passstrength').attr('class', 'alert');
$('#passstrength').html('Medium!');
} else {
$('#passstrength').attr('class', 'error');
$('#passstrength').html('Weak!');
}
return true;
});

5. 均衡元素的高度

使用纯CSS代码实现均衡元素的高度比较困难,而下面这段jQuery代码会根据最高的元素来均衡所有的Div元素:

var maxHeight = 0;
$("div").each(function() {
if ($(this).height() > maxHeight) {
maxHeight = $(this).height();
}
});
$("div").height(maxHeight);

6. 修复IE6 PNG问题

至今,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")');
});

7. 解析JSON字符串

使用jQuery解析JSON数据并不复杂。下面是一个高效解析JSON数据并将其追加到网页的例子:

function parseJson() {
// Start by calling the json object, I will be using a
// file from my own site for the tutorial
// Then we declare a callback function to process the data
$.getJSON('hcj.json', getPosts);

// The process function, I am going to get the title,
// url and excerpt for 5 latest posts
function getPosts(data) {
// Start a for loop with a limit of 5
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>';
// Append the body with the string
$('body').append(strPost);
}
}
}

// Fire off the function in your document ready
$(document).ready(function() {
parseJson();
});

8. 隔行换色

这是一个很经典的功能,在大的列表或表格中,隔行换色可以大大提高内容的可读性。下面的代码可以非常简单地实现这个功能:

$('div:odd').css("background-color", "#F4F4F8");
$('div:even').css("background-color", "#EFF1F1");

9. 预加载图片

你是否注意到Facebook相册的图片加载速度特别快?那是因为在你看到这些图片之前,它们已经被预加载到你的浏览器缓存中了。下面是实现类似功能的代码示例:

var nextimage = "/images/some-image.jpg";
$(document).ready(function() {
window.setTimeout(function() {
var img = $("<img>").attr("src", nextimage).load(function() {
// all done
});
}, 100);
});

10. 让整个Div可点击

这是实现链接的父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;
});

以上就是10个简单实用的jQuery代码片段,希望能对你的Web前端开发工作有所帮助。

作者信息

menghao

menghao

共发布了 3994 篇文章