jquery 有用代码片段




1、检测Internet Explorer版本
当涉及到CSS设计时,对开发者和设计者而言Internet Explorer一直是个问题。尽管IE6的黑暗时代已经过去,IE也越来越不流行,它始终是一个能够容易检测的好东西。当然了,下面的代码也能用于检测别的浏览器。
$(document).ready(function() {
if (navigator.userAgent.match(/msie/i) ){
alert('I am an old fashioned Internet Explorer');
}
});
2、平稳滑动到页面顶部
这是一个最广泛使用的jQuery效果:对一个链接点击下会平稳地将页面移动到顶部。这里没什么新的内容,但是每个开发者必须要会偶尔编写一下类似函数
$("a[href='#top']").click(function() {
$("html, body").animate({ scrollTop: 0 }, "slow");
return false;
});

	<a href="javascript:window.scrollTo(0, 0);" target="_self" class="aGoBackTop m8" id="BackTop" style="display: none;;"></a>

//自动隐藏

            $(document).bind('scroll',function(e){
                var sTop = $(this).scrollTop();
                if(sTop>260){
                    $('.return-top').show();
                }else{
                    $('.return-top').hide();
                }
            });

//滚动到自定位置
		<strong onclick="javascript:scroller('tbmov-movie', 300);">电影</strong>


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标志
jQuery使得用另外一个东西取代html标志很简单。可以利用的余地无穷无尽。
$('li').replaceWith(function(){
return $("<div />").append($(this).contents());
});
5、检测视窗宽度
现在移动设备比过时的电脑更普遍,能够方便去检测一个更小的视窗宽度会很有帮助。幸运的是,用jQuery来做超级简单。
var responsive_viewport = $(window).width();
/* if is below 481px */
if (responsive_viewport < 481) {
alert('Viewport is smaller than 481px.');
} /* end smallest screen */
6、自动定位并修复损坏图片
如果你的站点比较大而且已经在线运行了好多年,你或多或少会遇到界面上某个地方有损坏的图片。这个有用的函数能够帮助检测损坏图片并用你中意的图片替换它,并会将此问题通知给访客。
$('img').error(function(){
$(this).attr('src', 'img/broken.png');
});
7、检测复制、粘贴和剪切的操作
使用jQuery可以很容易去根据你的要求去检测复制、粘贴和剪切的操作。
$("#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”的属性
当链接到外部站点时,你可能使用target=”blank”的属性去在新界面中打开站点。问题在于target=”blank”属性并不是W3C有效的属性。让我们用jQuery来补救:下面这段代码将会检测是否链接是外链,如果是,会自动添加一个target=”blank”属性。
var root = location.protocol + '//' + 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;
}
});

DOM操作相关
嵌套的过滤器
//允许你减少集合中的匹配元素的过滤器,
//只剩下那些与给定的选择器匹配的部分。在这种情况下,
//查询删除了任何没(:not)有(:has)
//包含class为“selected”(.selected)的子节点。
.filter(":not(:has(.selected))")
找到节点索引号
$("ul > li").click(function  {
    var index = $(this).prevAll.length;
});
检测是否存在
if ($('#someDiv').length) {
//万岁!!!它存在……
}
动效相关
滑动到页面顶部
$("a[href='#top']").click(function {
  $("html, body").animate({ scrollTop: 0 }, "slow");
  return false;});
滚动到某位置
jQuery.fn.autoscroll = function(selector) {
    $('html,body').animate(
        {scrollTop: $(selector).offset.top},
        500
    };
}
//然后像这样来滚动到你希望去到的class/area上。
$('.area_name').autoscroll;
固定到顶部
允许一个元素固定到顶部
$(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')
    }}
出现在屏幕中心
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;
}
//这样来使用上面的函数:
$(element).center;
鼠标位置
$(document).ready(function {
    $(document).mousemove(function(e){
        $(’#XY’).html(”X Axis : ” + e.pageX + ” | Y Axis ” + e.pageY);
    });
});
性能优化与工程处理相关
预加载图片
jQuery.preloadImages = function {
    for(var i = 0; i < arguments.length; i++) {
        $("<img />").attr('src', arguments[i]);
    }
};
//用法
$.preloadImages('image1.gif', '/path/to/image2.png', 'some/image3.jpg');
自动定位并修复图片
$('img').error(function{
    $(this).attr('src', 'img/broken.png');});
禁用右键单击上下文菜单
$(document).bind('contextmenu',function(e){
    return false;
});
鼠标右键和左键
$("#someelement").on('click', function(e) {
    if( (!$.browser.msie && e.button == 0) || ($.browser.msie && e.button == 1) ) {
        alert("Left Mouse Button Clicked");
    } else if(e.button == 2) {
        alert("Right Mouse Button Clicked");
    }
});
限制textarea字符个数
jQuery.fn.maxLength = function(max){
    this.each(function{
        var type = this.tagName.toLowerCase;
        var inputType = this.type? this.type.toLowerCase : null;
        if(type == "input" && inputType == "text" || inputType == "password"){

//Apply the standard maxLength
 this.maxLength = max;
        }
        else if(type == "textarea"){
 this.onkeypress = function(e){
 var ob = e || event;
 var keyCode = ob.keyCode;
 var hasSelection = document.selection? document.selection.createRange.text.length > 0 : this.selectionStart != this.selectionEnd;
 return !(this.value.length >= max && (keyCode > 50 || keyCode == 32 || keyCode == 0 || keyCode == 13) && !ob.ctrlKey && !ob.altKey && !hasSelection);
 };
 this.onkeyup = function{
 if(this.value.length > max){
 this.value = this.value.substring(0,max);
 }
 };
        }
    });
};
//用法
$('#mytextarea').maxLength(500);
文本输入禁止使用空格
$('input.nospace').keydown(function(e) {
    if (e.keyCode == 32) {
        return false;
    }});


猜你喜欢

转载自946265172.iteye.com/blog/2293247