原文: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. 解决电脑需要切换IP带来的MySQL连接问题

    直接上代码: import socket #获取本机电脑名 myname = socket.getfqdn(socket.gethostname( )) #获取本机ip myip = socket.g ...

  2. spring boot实战读书笔记1

    1 覆盖起步依赖引入的传递依赖. 以Spring Boot的Web起步依赖为例,它传递依赖了Jackson JSON库.如果不想使用,可以使用 <exclusions>元素去除Jackso ...

  3. t:formvalid中定义callback函数

    如果dialog="true"的话       callback="@Override functionName" 调用的是当前页面的方法       call ...

  4. 音频特征提取——pyAudioAnalysis工具包

    作者:桂. 时间:2017-05-04  18:31:09 链接:http://www.cnblogs.com/xingshansi/p/6806637.html 前言 语音识别等应用离不开音频特征的 ...

  5. CSDN日报20170403 ——《该不该离职?它说了算!》

    [程序人生]该不该离职?它说了算! 作者:安晓辉 我在加油站工作,月薪扣除五险一金2000多.工作时间长,上班48小时歇息8小时. 今年单位改革把我们都外包出去了,承包人对我各种苛刻要求.有心辞职去干 ...

  6. 基于FPGA的异步FIFO设计

    今天要介绍的异步FIFO,可以有不同的读写时钟,即不同的时钟域.由于异步FIFO没有外部地址端口,因此内部采用读写指针并顺序读写,即先写进FIFO的数据先读取(简称先进先出).这里的读写指针是异步的, ...

  7. mysql删除账户

    mysql> select user,host,password from user; +------+-----------+--------------------------------- ...

  8. 配置maven为阿里云加速

    <repositories> <repository> <id>nexus-aliyun</id> <name>Nexus aliyun&l ...

  9. 登陆时不同浏览器获取session存在的相关疑问?

    问题1:在同一个电脑上,登陆成功后,将登陆信息存放到session域中后,使用另一个浏览器访问时,能否获取这个session域中的值? request.getSession().setAttribut ...

  10. dp之二维背包poj1837(天平问题 推荐)

    题意:给你c(2<=c<=20)个挂钩,g(2<=g<=20)个砝码,求在将所有砝码(砝码重1~~25)挂到天平(天平长  -15~~15)上,并使得天平平衡的方法数..... ...