原文: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;’ : ”);
}

最新文章

  1. 在WebApi中 集成 Swagger
  2. 分享SQL Server 2012/2014内存数据库,AlwaysOn,参考教材与网上总结
  3. QTableWidget详解(样式、右键菜单、表头塌陷、多选等) 2013-10-23 10:54:04
  4. 使用Eclipse进行远程调试【转】
  5. font awesome
  6. MYSQL注入天书之stacked injection
  7. ASP.NET MVC 学习第二天
  8. HDU4763 - Theme Section(KMP)
  9. iis的路径
  10. FTP原理和cent OS vsFTPd架设
  11. Keil C51汉字显示的bug问题(0xFD问题)
  12. cocos2dx 制作单机麻将(一)
  13. 讨论asp.net通过机器cookie仿百度(google)实现搜索input搜索提示弹出框自己主动
  14. php 常用的JS
  15. 跟版网 > 织梦教程 > 织梦安装使用 > 织梦DedeCMS附件上传大
  16. WatchKit编程指南:Watch Apps--文本、标签以及图片
  17. JavaScript 数组基础知识
  18. Codeforces Round #483 (Div. 2) C. Finite or not?
  19. js实现浏览器调用电脑的摄像头拍照
  20. 理解 if __name__ == &#39;__main__&#39;

热门文章

  1. python 下载.whl 文件,查看已安装软件包方法
  2. JavaScript / Html 转 pdf、图片
  3. 【转】获取scrollTop兼容各浏览器的方法,以及body和documentElement是啥?
  4. QT4编程过程中遇到的问题及解决办法
  5. 【JavaWeb】(10)微信公众号开发进阶
  6. vim:将刚写的单词大写和单词的定义
  7. 收集Cocos2d提供的字体!共57种
  8. JSP/Servlet中文乱码处理总结
  9. JAVA-MyEclipse第一个实例
  10. 基于jquery带时间轴的图片轮播切换代码