10个常用Jquery代码片段

来源:互联网 发布:学历网络教育学校 编辑:程序博客网 时间:2024/06/06 05:40

1、检测IE浏览器

$(document).ready(function(){    if(navigator.userAgent.match(/msie/i)){        alert('I am old fashioned Internet Explorer');    }});

2、平滑移动至页面顶部

$("a[href='#top']").click(function(){    $("html,body").animate({scrollTop:0},"slow");    return false;});

3、保持始终处于顶部

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


4、替换HTML标签

$('li').replaceWith(function(){    return $("<div/>").append($(this).contents());});


5、检测屏幕宽度

var responsive_viewport=$(window).width();/*if is below 481px*/if(responsive_viewport<481){    alert('Viewport is smaller than 481px.');}

6、自动修复损坏图片

$('img').error(function(){    $(this).attr('src','img/broken.png');});

7、检测复制、粘贴与剪切操作

$("#textA").bind('copy',function(){    $('span').text('copy behaviour detected!');});$("#textA").bind('paste',function(){    $('span').text('paste behaviour detected!');});$("#textA").bind('cut',function(){    $('span').text('cut behaviour detected');});

8、自动为外部链接添加target="blank"属性

var root=location.protocal+'//'+location.host;$('a').not(':contains(root)').click(function(){    this.target="_blank";});

9、悬停时淡入/淡出

$(document).ready(function(){    $(".thumbs img").fadeTo("slow",0.6);//This sets the opacity of the thumbs to fade down to 60% when the page loads    $(".thumbs img").hover(function(){        $(this).fadeTo("slow",1.0);//This should set the opacity to 100% on hover    },function(){        $(this).fadeTo("slow",0.6);//This should set the opacity back to 60% on mouseout    });});

10、禁用文本/密码输入中的空格

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


0 0
原创粉丝点击