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程式碼