原文: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实用代码片段(译)的更多相关文章

  1. javascript实用代码片段

    持续积累中~ 拓展原型 Function.prototype.method = function(name, extend) { if(!this.prototype[name]) { this.pr ...

  2. 100个直接可以拿来用的JavaScript实用功能代码片段(转载)

    把平时网站上常用的一些实用功能代码片段通通收集起来,方面网友们学习使用,利用好的话可以加快网友们的开发速度,提高工作效率. 目录如下: 1.原生JavaScript实现字符串长度截取2.原生JavaS ...

  3. JavaScript实用功能代码片段

    把平时网站上常用的一些实用功能代码片段通通收集起来,方面网友们学习使用,利用好的话可以加快网友们的开发速度,提高工作效率. 1.原生JavaScript实现字符串长度截取 function cutst ...

  4. 100个直接可以拿来用的JavaScript实用功能代码片段(转)

    把平时网站上常用的一些实用功能代码片段通通收集起来,方面网友们学习使用,利用好的话可以加快网友们的开发速度,提高工作效率. 目录如下: 1.原生JavaScript实现字符串长度截取2.原生JavaS ...

  5. 回归 | js实用代码片段的封装与总结(持续更新中...)

      上一次更博还是去年10月28号了,截至今天已经有整整4个月没有更新博客了,没更新博客不是代表不学了,期间我已经用vue做了两个项目,微信小程序做了一个项目,只是毕竟找到工作了,想偷偷懒,你懂的. ...

  6. PHP实用代码片段(三)

    1. 目录清单 使用下面的 PHP 代码片段可以在一个目录中列出所有文件和文件夹. function list_files($dir) { if(is_dir($dir)) { if($handle ...

  7. PHP实用代码片段(二)

    1. 转换 URL:从字符串变成超链接 如果你正在开发论坛,博客或者是一个常规的表单提交,很多时候都要用户访问一个网站.使用这个函数,URL 字符串就可以自动的转换为超链接. function mak ...

  8. C#程序员经常用到的10个实用代码片段 - 操作系统

    原文地址  如果你是一个C#程序员,那么本文介绍的10个C#常用代码片段一定会给你带来帮助,从底层的资源操作,到上层的UI应用,这些代码也许能给你的开发节省不少时间.以下是原文: 1 读取操作系统和C ...

  9. 几个有用的JavaScript/jQuery代码片段(转)

    1. 检查数据是否包含在Array中 //jQuery实现 jQuery.inArray("value", arr); // 使用方法: if( jQuery.inArray(&q ...

随机推荐

  1. mysql 行转列(存储过程)

    直接sql(自己抽离代码,无法和order by rand() 复用): select shit from( select 要累加的字段, @tt:=CONCAT(@tt,',',a.要累加的字段) ...

  2. 算法导论--装备线调度(升序&amp;&amp;降序输出)

    题意就先不用讲了吧,感觉自己还没有掌握核心的东西. //心得 //如何保持路径,递归的实现 #include<iostream> #include<cstdio> #inclu ...

  3. 巧用tail查看软件的安装进程

    我在使用perlbrew安装perl的时候,学到的一招,呵呵. 有时候,安装软件的时候,特别是手动安装的时候,没有什么提示信息,只能干等着,其实,可以使用tail命令来跟踪安装日志的尾部,来观察安装的 ...

  4. git使用(一)----git安装

    windows安装git msysgit是windows版本的Git 下载地址:https://git-for-windows.github.io/ 安装步骤 linux安装git https://g ...

  5. Class.getResourceAsStream和ClassLoader.getResourceAsStream方法

    项目中,有时候要读取当前classpath下的一些配置文件,下面介绍下Class.getResourceAsStream和ClassLoader.getResourceAsStream两种方法以及两者 ...

  6. 【Android】4.1 UI设计器

    分类:C#.Android.VS2015:创建日期:2016-02-06 开发人员可以用以下两种方式声明UI:一是通过.xml文件(不带预览界面)或者.axml文件(带预览界面)来描述:二是用C#代码 ...

  7. mongoose中的versionKey

    通过mongoose中的save方法保存记录时document文档默认最后会有一个字段"__v",这个字段表示该文档是否是刚刚创建的,如果是则字段"__v"的值 ...

  8. 解决Alt+/不弹出提示的问题

    依次打开eclipse上面的windows ——preferences ——General —— Keys, 在Scheme的下面有一个搜索框,在搜索框里面输入“Content asist”(我的Ec ...

  9. Thread中的join使用

    线程中的join方法就是用来等待一个线程完成它自己的全部任务之后才开启下一个进程,join(时间),则表示线程要执行完时间范围才开始下一个工作任务的执行!比如定义join(1500)必须在执行15s后 ...

  10. Failed to stop Abandoned connection cleanup thread

    刚才在测试一个用户登录程序的时候,是这么一个情况,在login.jsp登录之后,跳转到success.jsp页面 然后我修改了一个servlet,重新deploy到/WEB-INF/classes下( ...