jQuery.fn.autoscroll = function (selector) { $('html,body').animate( { scrollTop: $(this ).offset().top }, 500 ); } //用法 $('.area_name').autoscroll();
//如何禁用右鍵單擊上下文菜單 $(document).bind('contextmenu', function (e) { return false ; });
//如何檢查某個元素是否存在 if ($('#someDiv' ).length) { //你妹,終於找到了 }
//如何使用jQuery來切換樣式表 //找出你但願切換的媒體類型(media-type),而後把href設置成新的樣式表。 $('link[media="screen"]').attr('href', 'Alternative.css');
//如何替換串中的詞 var el = $('#id'); el.html(el.html().replace(/word/ig, ''));
//如何限制「Text-Area」域中的字符的個數 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") { 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);
//如何在jQuery中克隆一個元素 var cloned = $('#somediv').clone();
//在jQuery中如何測試某個元素是否可見 if ($(element).is(':visible') ) { //該元素是可見的 }
//如何把一個元素放在屏幕的中心位置 jQuery.fn.center = function () { this.css('position', 'absolute'); this.css('top', ($(window).height() - this.height()) / +$(window).scrollTop() + 'px'); this.css('left', ($(window).width() - this.width()) / 2 + $(window).scrollLeft() + 'px'); return this; } //這樣來使用上面的函數: $(element).center();
//如何從元素中除去HTML (function ($) { $.fn.stripHtml = function () { var regexp = /<("[^"]*"|'[^']*'|[^'">])*>/gi; this.each(function () { $(this).html($(this).html().replace(regexp, "")); }); return $(this); } })(jQuery); //用法: $('p').stripHtml();
//如何使用一個可點擊的連接來替換頁面中任何的URL $.fn.replaceUrl = function () { var regexp = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi; this.each(function () { $(this).html( $(this).html().replace(regexp, '<a href="$1">$1</a>') ); }); return $(this); } //用法 $('p').replaceUrl();