Javascript实用代码片段

原文:http://www.bestdesigntuts.com/10-time-saving-javascript-code-snippets-for-web-developers

1. 同高或同宽

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;
};

2. 日期验证-Date Validation

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 && d <= (new Date(y, m, 0)).getDate());   // Check if it’s a valid day of the month   }   return isDate(theDate, theFormat); }

3. 设置断点-Set Breakpoints

function isBreakPoint(bp) {

    // The breakpoints that you set in your css

    var bps = [320, 480, 768, 1024];

    var w = $(window).width();

    var min, max;

    for (var i = 0, l = bps.length; i < l; i++) {

         if (bps[i] === bp) { 

              min = bps[i-1] || 0;

              max = bps[i]; 

              break;    

         }  

     } 

    return w > min && w <= max;

}                     

4. Emphasize Text

A number of JavaScript libraries are available for highlighting text. However, there is an extremely simple way to do that:

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”>$&‘);
}
}
return text;
}

5. Animated Effects

Looking for providing interesting animated effects to your text? Use the following code snippet for this purpose:

$.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, ‘$&‘));
$this.find(’span.letter’).each(function(i, el){
setTimeout(function(){ $(el).addClass(klass); }, delay * i);
});
});
};

6. Fading Elements

A group of components can be made to fade using this code snippet:

$.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     $el.eq(i).delay(d).fadeIn(o.speed, o.ease);
}
return $el;
}

7. Counting Clicks

It may be required to count the number of times an element was clicked. The following code helps you to do that without complicating the code:

$(element)
.data(‘counter’, 0) // begin counter at zero
.click(function() {
var counter = $(this).data(‘counter’); // get
$(this).data(‘counter’, counter + 1); // set
// do something else…
});

8. Embed YouTube

Here is a code to embed YouTube videos along with custom parameters:
function embedYoutube(link, ops) {
var o = $.extend({
width: 480,
height: 320,
params: ”
}, ops);
var id = /\?v\=(\w+)/.exec(link)[1];
return ‘<iframe style=”display: block;”‘+
‘ type=”text/html”‘+
‘ width=”‘ + o.width + ‘” height=”‘ + o.height +
‘ “src=”http://www.youtube.com/embed/’ + id + ‘?’ + o.params +
‘&amp;wmode=transparent” frameborder=”0″ />’;
}

9. Create Active Menus

One can make use of the following script to generate menus in an animated fashion. There are several ways of creating a menu such as list, drop down and many more.
function makeMenu(items, tags) {
tags = tags || ['ul', 'li']; // default tags
var parent = tags[0];
var child = tags[1];
var item, value = ”;
for (var i = 0, l = items.length; i < l; i++) {
item = items[i];
// Separate item and value if value is present
if (/:/.test(item)) {
item = items[i].split(‘:’)[0];
value = items[i].split(‘:’)[1];
}
// Wrap the item in tag
items[i] = ‘<’+ child +’ ‘+
(value && ‘value=”‘+value+’”‘) +’>’+ // add value if present
item +’</’+ child +’>’;
}
return ‘<’+ parent +’>’+ items.join(”) +’</’+ parent +’>’;
}

10. Reduction of Text

Any text excerpt can be shortened to a specific length with the usage of this code:
function excerpt(str, nwords) {
var words = str.split(‘ ‘);
words.splice(nwords, words.length-1);
return words.join(‘ ‘) +
(words.length !== str.split(‘ ‘).length ? ‘&hellip;’ : ”);
}

你可能感兴趣的:(JavaScript)