超實用的JavaScript代碼段 附使用方法

字號:


    這篇文章主要為大家分享了10個短小又超實用的JavaScript代碼段 ,每個代碼段附使用方法,感興趣的朋友可以參考一下
    JavaScript一種直譯式腳本語言,是一種動態(tài)類型、弱類型、基于原型的語言,內(nèi)置支持類型。它的解釋器被稱為JavaScript引擎,為瀏覽器的一部分,廣泛用于客戶端的腳本語言,最早是在HTML(標(biāo)準(zhǔn)通用標(biāo)記語言下的一個應(yīng)用)網(wǎng)頁上使用,用來給HTML網(wǎng)頁增加動態(tài)功能。
    本文為大家整理了5段實用JavaScript代碼,便于大家進(jìn)行開發(fā)。
    1. 判斷日期是否有效
    JavaScript中自帶的日期函數(shù)還是太過簡單,很難滿足真實項目中對不同日期格式進(jìn)行解析和判斷的需要。JQuery也有一些第三方庫來使日期相關(guān)的處理變得簡單,但有時你可能只需要一個非常簡單的函數(shù),而不想引入一個龐大的第三方庫。這時,你可以使用下面這段日期校驗代碼,它允許你自定義日期格式并進(jìn)行日期有效性的校驗。
    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);
    }
    使用方法:
    下面這個調(diào)用返回false,因為11月份沒有31天
    isValidDate('dd-mm-yyyy', '31/11/2012')
    2. 獲取一組元素的最大寬度或高度
    下面這個函數(shù),對于需要進(jìn)行動態(tài)排版的開發(fā)人員非常有用。
    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的第三方庫可以實現(xiàn)高亮文本的功能,但我更喜歡用下面這一小段JavaScript代碼來實現(xiàn)這個功能,它非常短小,而且可以根據(jù)我的需要去進(jìn)行靈活的修改,而且可以自己定義高亮的樣式。下面這兩個函數(shù)可以幫助你創(chuàng)建自己的文本高亮插件。
    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 +'>$&</'+ tag +'>');
      }
     }
     return text;
    }
    你同樣會需要取消高亮的函數(shù):
    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插件代碼來達(dá)到這個效果。當(dāng)然你需要結(jié)合一個CSS3 transition樣式來達(dá)到更好的效果。
    $.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>$&</span>'));
      $this.find('span.letter').each(function(i, el){
       setTimeout(function(){ $(el).addClass(klass); }, delay * i);
      });
     });
    };
    使用方法:
    $('p').animateText(15, 'foo');
    5. 逐個隱藏元素
    下面這個jQuery插件可以根據(jù)你設(shè)置的步長(間隔時間)來逐個隱藏一組元素。在列表元素的重新加載中使用,可以達(dá)到很好的效果。
    $.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代碼段中的一小部分,希望對大家學(xué)習(xí)javascript程序設(shè)計有所幫助。