---
title: "9 个超实用的 jQuery 代码片段"
author: "wangxiaoxu"
date: "2013-07-15T14:49:42Z"
tags: []
categories: ["Web前端"]
slug: "9-jquery"
draft: false
lastmod: "2013-07-15T14:49:42Z"
id: 1906546
url: "https://wangxiaoxu.iteye.com/blog/1906546"
---

jQuery以其强大的功能和简单的使用成为了前端开发者最喜欢的JS类库，在这里我们分享一组实用的jQuery代码片段，希望大家喜欢！ 

**1.  jQuery平滑回到顶端效果** 

Javascript代码 

01. $(document).ready(function() {
02. $("a.topLink").click(function() {
03. $("html, body").animate({
04. scrollTop: $($(this).attr("href")).offset().top + "px"
05. }, {
06. duration: 500,
07. easing: "swing"
08. });
09. return false;
10. });
11. });

[在线调试](http://www.gbin1.com/gb/debug/20864b59-a995-4318-a242-b3038f83f2c3.htm) 

**2.  jQuery处理图片尺寸** 

Javascript代码 

01. $(window).bind("load", function() {
02. // 图片修改大小
03. $('#imglist img').each(function() {
04. var maxWidth = 120;
05. var maxHeight = 120;
06. var ratio = 0;
07. var width = $(this).width();
08. var height = $(this).height();
09. if(width &gt; maxWidth){
10. ratio = maxWidth / width;
11. $(this).css("width", maxWidth);
12. $(this).css("height", height * ratio);
13. height = height * ratio;
14. }
15. if(height &gt; maxHeight){
16. ratio = maxHeight / height;
17. $(this).css("height", maxHeight);
18. $(this).css("width", width * ratio);
19. width = width * ratio;
20. }
21. });
22. });

[在线调试](http://www.gbin1.com/gb/debug/5a2271a5-f363-4b34-8d2f-f0ad03121ced.htm) 

**3.  jQuery实现的滚动自动加载代码** 

Javascript代码 

01. var loading = false;
02. $(window).scroll(function(){
03. if((($(window).scrollTop()+$(window).height())+250)&gt;=$(document).height()){
04. if(loading == false){
05. loading = true;
06. $('#loadingbar').css("display","block");
07. $.get("load.php?start="+$('#loaded\_max').val(), function(loaded){
08. $('body').append(loaded);
09. $('#loaded\_max').val(parseInt($('#loaded\_max').val())+50);
10. $('#loadingbar').css("display","none");
11. loading = false;
12. });
13. }
14. }
15. });
16. $(document).ready(function() {
17. $('#loaded\_max').val(50);
18. });

**4.  jQuery测试密码强度** 

Javascript代码 

01. $('#pass').keyup(function(e) {
02. var strongRegex = new RegExp("^(?=.{8,})(?=.\*\[A-Z])(?=.\*\[a-z])(?=.\*\[0-9])(?=.\*\\W).\*$", "g");
03. var mediumRegex = new RegExp("^(?=.{7,})(((?=.\*\[A-Z])(?=.\*\[a-z]))|((?=.\*\[A-Z])(?=.\*\[0-9]))|((?=.\*\[a-z])(?=.\*\[0-9]))).\*$", "g");
04. var enoughRegex = new RegExp("(?=.{6,}).\*", "g");
05. if (false == enoughRegex.test($(this).val())) {
06. $('#passstrength').html('More Characters');
07. } else if (strongRegex.test($(this).val())) {
08. $('#passstrength').className = 'ok';
09. $('#passstrength').html('Strong!');
10. } else if (mediumRegex.test($(this).val())) {
11. $('#passstrength').className = 'alert';
12. $('#passstrength').html('Medium!');
13. } else {
14. $('#passstrength').className = 'error';
15. $('#passstrength').html('Weak!');
16. }
17. return true;
18. });

[在线调试](http://www.gbin1.com/gb/debug/5ae6bca8-b12b-48b8-861a-8d9ab09e6641.htm) 

**5.  jQuery实现的DIv高度保持一致** 

Javascript代码 

1. var maxHeight = 0;
2. $("div").each(function(){
3. if ($(this).height() &gt; maxHeight) { maxHeight = $(this).height(); }
4. });
5. $("div").height(maxHeight);

[在线调试](http://www.gbin1.com/gb/debug/ac7c5175-9282-41c0-a766-c56707946c7b.htm) 

**6.  简单处理IE6上PNG格式文件** 

Javascript代码 

1. $('.pngfix').each( function() {
2. $(this).attr('writing-mode', 'tb-rl');
3. $(this).css('background-image', 'none');
4. $(this).css( 'filter', 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="path/to/image.png",sizingMethod="scale")');
5. });

将class=pngfix添加到需要处理的对象即可。 

**7.  jQuery处理JSON** 

Javascript代码 

01. function parseJson(){
02. //Start by calling the json object, I will be using a
03. //file from my own site for the tutorial
04. //Then we declare a callback function to process the data
05. $.getJSON('hcj.json',getPosts);
06. //The process function, I am going to get the title,
07. //url and excerpt for 5 latest posts
08. function getPosts(data){
09. //Start a for loop with a limit of 5
10. for(var i = 0; i &lt; 5; i++){
11. //Build a template string of
12. //the post title, url and excerpt
13. var strPost = '&lt;h2&gt;'
14. + data.posts\[i].title
15. + '&lt;/h2&gt;'
16. + '&lt;p&gt;'
17. + data.posts\[i].excerpt
18. + '&lt;/p&gt;'
19. + '&lt;a href="'
20. + data.posts\[i].url
21. + '" title="Read '
22. + data.posts\[i].title
23. + '"&gt;Read &gt;&lt;/a&gt;';
24. //Append the body with the string
25. $('body').append(strPost);
26. }
27. }
28. }
29. //Fire off the function in your document ready
30. $(document).ready(function(){
31. parseJson();
32. });

**8.  jQuery实现让整个div可以被点击** 

Javascript代码 

1. $(".myBox").click(function(){      window.location=$(this).find("a").attr("href");       return false; });

[在线调试](http://www.gbin1.com/gb/debug/4bfb3dce-1681-470c-b47a-7490df12f3b0.htm) 

**9.  jQuery实现的Facebook风格的图片预加载效果** 

Javascript代码 

1. var nextimage = "http://www.gbtags.com/gb/networks/uploadimgthumb/55d67b14-fb25-45e7-acc8-211a41047ef0.jpg";
2. $(document).ready(function(){
3. window.setTimeout(function(){
4. var img = $("&lt;img&gt;").attr("src", nextimage).load(function(){
5. $('div').append(img);
6. });
7. }, 100);
8. });
9. \[url=http://www.gbin1.com/gb/debug/b1a87e30-e33f-4369-92fc-55e8fd628816.htm]在线调试\[/url]

希望大家喜欢这些实用的jQuery代码，如果你也有更多的jQuery代码片段，请与我们分享，谢谢！