1. 使用jQuery来切换样式表

//找出你希望切换的媒体类型(media-type),然后把href设置成新的样式表。
$(‘link[media="screen"]‘).attr(‘href’, ’Alternative.css’);

2. 设置IE特有的功能

if ($.browser.msie) {
  // Internet Explorer其实不那么好用
}

3. 验证某个元素是否为空

if ($(‘#keks’).html().trim()) {
  //什么都没有找到;
}

4. 检查某个元素是否存在

if ($(‘#someDiv’ ).length) {
  //你妹,终于找到了
}

5.验证某个元素是否为空:

// 方法一
if (! $('#keks').html()) {
//什么都没有找到
} // 方法二
if ($('#keks').is(":empty")) {
//什么都没有找到
}

6. 找到一个已经被选中的option元素

$(‘#someElement’).find(‘option:selected’);

7. 禁用右键单击上下文菜单

$(document).bind(‘contextmenu’, function (e) {
  return false ;
});

8、设定计时器

$(document).ready(function() {
window.setTimeout(function() {
// some code
}, 500);
});

9、设置等高的列

<div class="equalHeight" style="border:1px solid">
   <p>First Line</p>
   <p>Second Line</p>
   <p>Third Line</p>
</div>
<div class="equalHeight" style="border:1px solid">
   <p>Column Two</p>
</div>
<script src="http://apps.bdimg.com/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
   equalHeight('.equalHeight');
});
//global variable, this will store the highest height value
var maxHeight = 0;
function equalHeight(col) {
  //Get all the element with class = col
  col = $(col);
   //Loop all the col
   col.each(function() {
  //Store the highest value
if ($(this).height() > maxHeight) {
   maxHeight = $(this).height();
}
});
  //Set the height
  col.height(maxHeight);
}
</script>

10、jQuery预加载图像

jQuery.preloadImagesInWebPage = function() {
   for (var ctr = 0; ctr & lt; 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…');
});

11、把元素定位到页面中间

<div id="foo" style="width:200px;height: 200px;background: #ccc;"></div>
<script src="http://apps.bdimg.com/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery.fn.center = function() {
   this.css("position", "absolute");
   this.css("top", ($(window).height() - this.height()) / 2 + $(window).scrollTop() + "px");
   this.css("left", ($(window).width() - this.width()) / 2 + $(window).scrollLeft() + "px");
  return this;
}
//Use the above function as:
$('#foo').center();
</script>

12、禁用鼠标右键

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

13、计算子元素的个数

<div id="foo">
<div id="bar"></div>
<div id="baz">
<div id="biz"></div>
<span><span></span></span>
</div>
</div>
<script src="http://apps.bdimg.com/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
//jQuery code to count child elements $("#foo > div").size()
alert($("#foo > div").size())
</script>

14、检测当前鼠标坐标

$(document).ready(function() {
  $().mousemove(function(e){
    $('# MouseCoordinates ').html("X Axis Position = " + e.pageX + " and Y Axis Position = " + e.pageY);
  });

15、获取鼠标指针的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);
});

16、返回到顶部链接

$(document).ready(function() {
    //when the id="top" link is clicked
    $('#top').click(function() {
    //scoll the page back to the top
    $(document).scrollTo(0,500);
  }
});

16-1:平滑滚动返回顶端

<h1 id="anchor">admin10000.com</h1>
<a class="topLink" href="#anchor">返回顶端</a> $(document).ready(function () { $("a.topLink").click(function () {
$("html, body").animate({
scrollTop: $($(this).attr("href")).offset().top + "px"
}, {
duration: 500,
easing: "swing"
});
return false;
}); });

17、导航菜单背景切换效果

<ul id='nav'>
<li>导航一</li>
<li>导航二</li>
<li>导航三</li>
</ul>
//注意:代码需要修饰完善
$('#nav').click(function(e) {
// 要知道siblings的使用
$(e.target).addClass('tclass').siblings('.tclass').removeClass('tclass');;
});

18、反序访问JQuery对象里的元素

//在某些场景下,我们可能需要反序访问通过JQuery选择器获取到的页面元素对象,这个怎么实现呢?看下面代码:

//要掌握JQuery对象的get方法 以及数组的reverse方法即可
var arr = $('#nav').find('li').get().reverse();
$.each(arr,function(index,ele){
.... ...
});

19、 管理搜索框的值

现在各大网站都有搜索框,而搜索框通常都有默认值,当输入框获取焦点时,默认值消失。而一旦输入框失去焦点,而输入框里又没有输入新的值,输入框里的值又会恢复成默认值,如果往输入框里输入了新值,则输入框的值为新输入的值。这种特效用JQuery很容易实现:

$("#searchbox")
.focus(function(){$(this).val('')})
.blur(function(){
var $this = $(this);
// '请搜索...'为搜索框默认值
($this.val() === '')? $this.val('请搜索...') : null;
});

20、部分页面内容的延时加载更新

为了提高web性能,有更新时我们通常不会加载整个页面,而只是仅仅更新部分页面内容,如图片的延迟加载等。页面部分刷新的特效在JQuery中也很容易实现:

setInterval(function() {  //每隔5秒钟刷新页面内容
//获取的内容将增加到 id为content的元素后
$("#content").load(url);
}, 5000);

21、采用data方法来缓存数据

在项目中,为了避免多次重复的向服务器请求数据,通常会将获取的数据缓存起来以便后续使用。通过JQuery可以很优雅的实现该功能:

var cache = {};
$.data(cache,'key','value'); //缓存数据
//获取数据
$.data(cache,'key');

22、采配置JQuery与其它库的兼容性

如果在项目中使用JQuery,$ 是最常用的变量名,但JQuery并不是唯一一个使用$作为变量名的库,为了避免命名冲突,你可以按照下面方式来组织你的代码:

//方法一: 为JQuery重新命名为 $j

var $j = jQuery.noConflict();
$j('#id')....
//方法二: 推荐使用的方式 (function($){
$(document).ready(function(){
//这儿,你可以正常的使用JQuery语法
});
})(jQuery);

23、根据视窗(viewport)创建一个全屏宽度和高度(width/height)的div

下面代码完全可以让你根据viewport创建一个全屏的div。这对在不同窗口大小下展示modal或对话框时非常有效:

$('#content').css({
'width': $(window).width(),
'height': $(window).height(),
});
// make sure div stays full width/height on resize
$(window).resize(function(){
var $w = $(window);
$('#content').css({
'width': $w.width(),
'height': $w.height(),
});
});

24、测试密码的强度

在某些网站注册时常常会要求设置密码,网站也会根据输入密码的字符特点给出相应的提示,如密码过短、强度差、强度中等、强度强等。这又是怎么实现的呢?看下面代码:

<input type="password" name="pass" id="pass" />
<span id="passstrength"></span>
//下面的正则表达式建议各位收藏哦,项目上有可能会用得着
$('#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').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;
});

25、使用JQuery重绘图片的大小

关于图片大小的重绘,你可以在服务端来实现,也可以通过JQuery在客户端实现。

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

26、滚动时动态加载页面内容

有些网站的网页内容不是一次性加载完毕的,而是在鼠标向下滚动时动态加载的,这是怎么做到的呢?看下面代码:

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

27、获取 URL 中传递的参数

$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (!results) { return 0; }
return results[1] || 0;
}

28、禁用表单的回车键提交

$("#form").keypress(function(e) {
  if (e.which == 13) {
   return false;
   }
});

更多资源:http://www.jb51.net/article/74428.htm

jquery代码小片段的更多相关文章

  1. 49个jquery代码经典片段

    49个jquery代码经典片段,这些代码能够给你的javascript项目提供帮助.其中的一些代码段是从jQuery1.4.2才开始支持的做法,另一些则是真正有用的函数或方法,他们能够帮助你又快又好地 ...

  2. 49 个jquery代码经典片段

    49 个jquery代码经典片段,这些代码能够给你的javascript项目提供帮助.其中的一些代码段是从jQuery1.4.2才开始支持的做法,另一 些则是真正有用的函数或方法,他们能够帮助你又快又 ...

  3. Python代码小片段

    1.前面变量值的改变不影响后面变量的调用 index=1 index,a=2,index+1 print(a,index) #2 2 2.类的继承(子类实例如何调用父类同名方法) class a: d ...

  4. JavaScript 代码小片段

    1.获取对象 obj 的所有属性(自有属性和继承属性),保存到数组 lst 中 //获取对象obj的所有属性(自有属性和继承属性),保存到数组lst 中 var lst = []; function ...

  5. 实用的 CSS 小片段

    看了 30 Seconds CSS,有了许多收获,所以写下了这篇文章,算是收藏一些代码小片段,留作后用. 一.手写 Loading 动画 (1)弹性加载动画 CSS 代码如下: .bounce-loa ...

  6. 高效Web开发的10个jQuery代码片段(10 JQUERY SNIPPETS FOR EFFICIENT WEB DEVELOPMENT)

    在过去的几年中,jQuery一直是使用最为广泛的JavaScript脚本库.今天我们将为各位Web开发者提供10个最实用的jQuery代码片段,有需要的开发者可以保存起来. 1.检测Internet ...

  7. Web开发者必须知道的10个jQuery代码片段

    在过去的几年中,jQuery一直是使用最为广泛的JavaScript脚本库.今天我们将为各位Web开发者提供10个最实用的jQuery代码片段,有需要的开发者可以保存起来. 1.检测Internet ...

  8. Jquery学习总结(4)——高效Web开发的10个jQuery代码片段

    在过去的几年中,jQuery一直是使用最为广泛的JavaScript脚本库.今天我们将为各位Web开发者提供10个最实用的jQuery代码片段,有需要的开发者可以保存起来. 1.检测Internet ...

  9. 经验分享:10个简单实用的 jQuery 代码片段

    尽管各种 JavaScirpt 框架和库层出不穷,jQuery 仍然是 Web 前端开发中最常用的工具库.今天,向大家分享我觉得在网站开发中10个简单实用的 jQuery 代码片段. 您可能感兴趣的相 ...

随机推荐

  1. linux系统初始化——busybox的inittab文件格式说明

    busybox的inittab文件格式说明 要写自己的inittab,需要理解busybox的inittab文件格式. busybox的inittab文件与通常的inittab不同,它没有runlev ...

  2. [暑假集训--数论]poj1595 Prime Cuts

    A prime number is a counting number (1, 2, 3, ...) that is evenly divisible only by 1 and itself. In ...

  3. Python之面向对象:属性

    一.属性定义 1.类属性 类属性定义在类中且在函数体之外:类属性通常不作为实例属性使用:类变量紧接在类名后面定义 类属性的引用:类名.count eg:Employee.count 实例中可以引用类的 ...

  4. POJ3311 Hie with the Pie

    The Pizazz Pizzeria prides itself in delivering pizzas to its customers as fast as possible. Unfortu ...

  5. *LOJ#2306. 「NOI2017」蔬菜

    $n \leq 100000$种蔬菜,每个蔬菜有:一单位价格:卖第一单位时额外价格:总量:每天腐烂量.每天能卖$m \leq 10$单位蔬菜,多次询问:前$k \leq 100000$天最多收入多少. ...

  6. EasySlider-最简洁的JQuery滚动插件 可控制滚动

    原文发布时间为:2010-05-05 -- 来源于本人的百度文章 [由搬家工具导入] Easy Silder是由Alen Grakalic开发的基于JQuery的滚动插件,它支持以下功能: 1.自动滚 ...

  7. DataSet导出到Excel文件

    public static void ExportToExcel(DataSet source, string fileName) { System.IO.StreamWriter excelDoc ...

  8. [LeetCode] Gas Station 贪心

    There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. You ...

  9. C++学习(一):现代C++尝试

    C++是一门与时俱进的语言. 早期的C++关注的主要问题是通用性,却没有太多关注易用性的问题,使得C++成为了一门多范式语言,但是使用门槛较高. 从2011开始,C++的标准进行了较大的更新,开始更多 ...

  10. unittest框架及自动化测试

    之前在公司做过自动化测试的知识分享,现在把它记录下来.   •一.如何更好的编写测试用例 •1.模块化:将一些基础的.共有的步骤代码独立为单独的模块,使用时再调用.好处:可以使代码复用,减少代码编写, ...