【有用】须要珍藏备用的JQuery代码片断

1 元素屏幕居中

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;
}
$("#myDiv").center();

2 猎取页面途径相干参数

//值:http://42du.cn/list#jq
var url = document.URL;
//值:http:
var protocol = location.protocol;
//值:42du.cn
var host = location.host;
//值:jq
var hashP = document.URL.split('#')[1];

3 删除内联款式

$("*[style]").attr("style", "");

4 长度限定并截取

var $elem = $("#title");
if($elem.text().length > 30) {
    $elem.text($elem.text().substr(0, 27)+"...");
}

5 外链新窗口翻开

$("a[@href^='http']").attr('target','_blank');

6 测试JQuery与别的库争执状况

//测试争执代码
$("#jqtest").click( function() {
   alert("jQuery is working!");
});
//防止争执
var $jq = jQuery.noConflict();
$jq("#jqtest").click( function() {
   alert("jQuery is working!");
});

7 加载JQuery纵然CDN掉线

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="/media/js/jquery.js"><\/script>')</script>

8 加载遮罩层,点击移除

$('<div id="overlay"></div>')
.css({
    position    : 'fixed',
    top         : 0,
    left        : 0,
    right       : 0,
    bottom      : 0,
    opacity     : 0.6,
    background  : 'black',
    display     : 'none'
})
.appendTo('body')
.fadeIn('normal')
.click(function () {
    $(this).fadeOut('normal', function () {
        $(this).remove();
    })
});

9 元素固顶

//注重调解边境值
$(window).scroll(function() {
    if ($(window).scrollTop() > 100) {
        $('#navbar').css({'position' : 'fixed', 'top' : 0});
    } else {
        $('#navbar').css({'position' : 'relative', 'top' : 'none'});
    }
});

10 制止右键菜单

$(document).bind('contextmenu', function () {
    return false;
})

11 对象插件模版代码

(function($){
   var MyPlugin = function(element, options) {
       var elem = $(element);
       var obj = this;
       var settings = $.extend({param: 'defaultValue'}, options || {});
       // 公有要领
       this.publicMethod = function(){
           console.log('public method called!');
       };
       // 私有要领
       var privateMethod = function() {
           console.log('private method called!');
       };
   };
   $.fn.myplugin = function(options) {
       return this.each(function(){
           var element = $(this);
           // Return early if this element already has a plugin instance
           if (element.data('myplugin')) return;
           // pass options to plugin constructor
           var myplugin = new MyPlugin(this, options);
           // Store plugin object in this element's data
           element.data('myplugin', myplugin);
       });
   };
})(jQuery);

12 延长浏览

处置惩罚表单的JQuery代码

提拔机能的JQuery代码

    原文作者:毛瑞
    原文地址: https://segmentfault.com/a/1190000009613390
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞