jquery代码小片段

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="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

 

 

 

 

原文地址:https://www.cnblogs.com/xiangru0921/p/6543075.html