超實用的JavaScript程式碼片段 附使用方法_javascript技巧

來源:互聯網
上載者:User

JavaScript一種直譯式指令碼語言,是一種動態類型、弱類型、基於原型的語言,內建支援類型。它的解譯器被稱為JavaScript引擎,為瀏覽器的一部分,廣泛用於用戶端的指令碼語言,最早是在HTML(標準通用標記語言 (SGML)下的一個應用)網頁上使用,用來給HTML網頁增加動態功能。

本文為大家整理了5段實用JavaScript代碼,便於大家進行開發。

1. 判斷日期是否有效

JavaScript中內建的日期函數還是太過簡單,很難滿足真實項目中對不同日期格式進行解析和判斷的需要。JQuery也有一些第三方庫來使日期相關的處理變得簡單,但有時你可能只需要一個非常簡單的函數,而不想引入一個龐大的第三方庫。這時,你可以使用下面這段日期校正代碼,它允許你自訂日期格式並進行日期有效性的校正。

function isValidDate(value, userFormat) { // Set default format if format is not provided userFormat = userFormat || 'mm/dd/yyyy'; // Find custom delimiter by excluding // month, day and year characters var delimiter = /[^mdy]/.exec(userFormat)[0]; // Create an array with month, day and year // so we know the format order by index var theFormat = userFormat.split(delimiter); // Create array from user date var theDate = value.split(delimiter); function isDate(date, format) {  var m, d, y, i = 0, len = format.length, f;  for (i; i < len; i++) {   f = format[i];   if (/m/.test(f)) m = date[i];   if (/d/.test(f)) d = date[i];   if (/y/.test(f)) y = date[i];  }  return (   m > 0 && m < 13 &&   y && y.length === 4 &&   d > 0 &&   // Check if it's a valid day of the month   d <= (new Date(y, m, 0)).getDate()  ); } return isDate(theDate, theFormat);}

使用方法:
下面這個調用返回false,因為11月份沒有31天

isValidDate('dd-mm-yyyy', '31/11/2012')

2. 擷取一組元素的最大寬度或高度

下面這個函數,對於需要進行動態排版的開發人員非常有用。

var getMaxHeight = function ($elms) { var maxHeight = 0; $elms.each(function () {  // In some cases you may want to use outerHeight() instead  var height = $(this).height();  if (height > maxHeight) {   maxHeight = height;  } }); return maxHeight;};

使用方法:

$(elements).height( getMaxHeight($(elements)) );

3. 高亮文本

有很多JQuery的第三方庫可以實現高亮文本的功能,但我更喜歡用下面這一小段JavaScript代碼來實現這個功能,它非常短小,而且可以根據我的需要去進行靈活的修改,而且可以自己定義高亮的樣式。下面這兩個函數可以協助你建立自己的文本高亮外掛程式。

function highlight(text, words, tag) { // Default tag if no tag is provided tag = tag || 'span'; var i, len = words.length, re; for (i = 0; i < len; i++) {  // Global regex to highlight all matches  re = new RegExp(words[i], 'g');  if (re.test(text)) {   text = text.replace(re, '<'+ tag +' class="highlight">$&</'+ tag +'>');  } } return text;}

你同樣會需要取消高亮的函數:

function unhighlight(text, tag) { // Default tag if no tag is provided tag = tag || 'span'; var re = new RegExp('(<'+ tag +'.+?>|<\/'+ tag +'>)', 'g'); return text.replace(re, '');}

使用方法:

$('p').html( highlight(  $('p').html(), // the text  ['foo', 'bar', 'baz', 'hello world'], // list of words or phrases to highlight  'strong' // custom tag));

4. 文字動效

有時你會希望給你的一段文字增加動效,讓其中的每個字都動起來。你可以使用下面這段jQuery外掛程式代碼來達到這個效果。當然你需要結合一個CSS3 transition樣式來達到更好的效果。

$.fn.animateText = function(delay, klass) { var text = this.text(); var letters = text.split(''); return this.each(function(){  var $this = $(this);  $this.html(text.replace(/./g, '<span class="letter">$&</span>'));  $this.find('span.letter').each(function(i, el){   setTimeout(function(){ $(el).addClass(klass); }, delay * i);  }); });};

使用方法:

$('p').animateText(15, 'foo');

5. 逐個隱藏元素

下面這個jQuery外掛程式可以根據你設定的步長(間隔時間)來逐個隱藏一組元素。在列表元素的重新載入中使用,可以達到很好的效果。

$.fn.fadeAll = function (ops) { var o = $.extend({  delay: 500, // delay between elements  speed: 500, // animation speed  ease: 'swing' // other require easing plugin }, ops); var $el = this; for (var i=0, d=0, l=$el.length; i<l; i++, d+=o.delay) {  $el.eq(i).delay(d).fadeIn(o.speed, o.ease); } return $el;}

使用方法:

$(elements).fadeAll({ delay: 300, speed: 300 });

以上只是那些實用JavaScript程式碼片段中的一小部分,希望對大家學習javascript程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.