jQuery的常用小例子

212 阅读1分钟

1.文本/密码禁输入空格

$('input').keydown(function(e) { 
    if (e.keyCode == 32) {   
        return false; 
     }
});

2.检测屏幕宽度

var width= $(window).width(); 

3.替换html标签

//用粗体文本替换每个段落
$(".btn1").click(function(){
   $("p").replaceWith("<b>Hello world!</b>");//规定替换被选元素的内容
});

//replaceWith() 方法用指定的 HTML 内容或元素替换被选元素。
//提示:replaceWith() 与 replaceAll() 作用相同。
//差异在于语法:内容和选择器的位置,以及 replaceAll() 无法使用函数进行替换。

//使用函数来替换元素
$("p").replaceWith(function(){
  return "<p>Hello World!</p>";
});

//$(selector).replaceWith(function())//function()返回待替换被选元素的新内容的函数

4.平滑滚动至页面顶部

//回到顶部按钮:利用jQuery里的animate和scrollTop方法
$(".top").click(function(e) {
    e.preventDefault();   
    $("html, body").animate({ scrollTop: 0 }, 800);
    return false;
}); 

//某一元素始终处于页面顶部
$(function(){
    var $win = $(window); 
    var $nav = $('.mytoolbar');
    var navTop = $('.mytoolbar').length && $('.mytoolbar').offset().top;   
    var isFixed=0;  

      processScroll(); 
      $win.on('scroll', processScroll);

     function processScroll() {  
         var i, scrollTop = $win.scrollTop(); 
         if (scrollTop >= navTop && !isFixed) {  
             isFixed = 1 ;
             $nav.addClass('subnav-fixed');
         } else if (scrollTop <= navTop && isFixed) {   
            isFixed = 0;
            $nav.removeClass('subnav-fixed');
     }  
 }

5.复制、粘贴与剪切

$("span").bind('copy', function() { 
    $('span').text('copy');
});  

$("span").bind('paste', function() {   
    $('span').text('paste');
 });
  
$("span").bind('cut', function() { 
    $('span').text('cut')   
});

6.自动为外部链接添加target=“blank”属性

var root = location.protocol + '//' + location.host; 

//当前链接是否指向外部,是则自动为其添加target="blank"属性
$('a').not(':contains(root)').click(function(){ 
    this.target = "_blank";
});

原文标题:10 jQuery Snippets for Efficient Web Development