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
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 +‘&wmode=transparent” frameborder=”0″ />’;}
9. Create Active Menus
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 tagsvar 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 presentif (/:/.test(item)) {item = items[i].split(‘:’)[0];value = items[i].split(‘:’)[1];}// Wrap the item in tagitems[i] = ‘<’+ child +’ ‘+(value && ‘value=”‘+value+’”‘) +’>’+ // add value if presentitem +’</’+ child +’>’;}return ‘<’+ parent +’>’+ items.join(”) +’</’+ parent +’>’;}
10. Reduction of Text
function excerpt(str, nwords) {var words = str.split(‘ ‘);words.splice(nwords, words.length-1);return words.join(‘ ‘) +(words.length !== str.split(‘ ‘).length ? ‘…’ : ”);}
Javascript实用代码片段(译)的更多相关文章
- javascript实用代码片段
持续积累中~ 拓展原型 Function.prototype.method = function(name, extend) { if(!this.prototype[name]) { this.pr ...
- 100个直接可以拿来用的JavaScript实用功能代码片段(转载)
把平时网站上常用的一些实用功能代码片段通通收集起来,方面网友们学习使用,利用好的话可以加快网友们的开发速度,提高工作效率. 目录如下: 1.原生JavaScript实现字符串长度截取2.原生JavaS ...
- JavaScript实用功能代码片段
把平时网站上常用的一些实用功能代码片段通通收集起来,方面网友们学习使用,利用好的话可以加快网友们的开发速度,提高工作效率. 1.原生JavaScript实现字符串长度截取 function cutst ...
- 100个直接可以拿来用的JavaScript实用功能代码片段(转)
把平时网站上常用的一些实用功能代码片段通通收集起来,方面网友们学习使用,利用好的话可以加快网友们的开发速度,提高工作效率. 目录如下: 1.原生JavaScript实现字符串长度截取2.原生JavaS ...
- 回归 | js实用代码片段的封装与总结(持续更新中...)
上一次更博还是去年10月28号了,截至今天已经有整整4个月没有更新博客了,没更新博客不是代表不学了,期间我已经用vue做了两个项目,微信小程序做了一个项目,只是毕竟找到工作了,想偷偷懒,你懂的. ...
- PHP实用代码片段(三)
1. 目录清单 使用下面的 PHP 代码片段可以在一个目录中列出所有文件和文件夹. function list_files($dir) { if(is_dir($dir)) { if($handle ...
- PHP实用代码片段(二)
1. 转换 URL:从字符串变成超链接 如果你正在开发论坛,博客或者是一个常规的表单提交,很多时候都要用户访问一个网站.使用这个函数,URL 字符串就可以自动的转换为超链接. function mak ...
- C#程序员经常用到的10个实用代码片段 - 操作系统
原文地址 如果你是一个C#程序员,那么本文介绍的10个C#常用代码片段一定会给你带来帮助,从底层的资源操作,到上层的UI应用,这些代码也许能给你的开发节省不少时间.以下是原文: 1 读取操作系统和C ...
- 几个有用的JavaScript/jQuery代码片段(转)
1. 检查数据是否包含在Array中 //jQuery实现 jQuery.inArray("value", arr); // 使用方法: if( jQuery.inArray(&q ...
随机推荐
- nginx php-fpm 输出php错误日志(转)
nginx是一个web服务器,因此nginx的access日志只有对访问页面的记录,不会有php 的 error log信息. nginx把对php的请求发给php-fpm fastcgi进程来处理, ...
- Dom4j解析和sax解析xml
xml基础知识 1)标签对大小写敏感,2)xml解析方式有两种dom解析和sax解析 3)常用的解析工具有dom的dom4j和sax的sax解析工具 4)文档声明中使用<?xml versio ...
- unity5 Text
unity5中,添加Text对象: 在其它对象的脚本中如果想引用此Text,则应定义: public UnityEngine.UI.Text myText; 然后把对象拖到变量上即可. 注: 1,需要 ...
- 怎么修改Elasticsearch的对外ip 默认是本地IP 127.0.0.1
//修改C:\Program Files\elasticsearch-2.1.1\config\elasticsearch.yml: network.bind_host: 172.16.1.86 pa ...
- Redis(一):概述
1.Redis解释 Redis 是一个基于key-value形式进行存储的内存型数据库. 1.1 数据存储方式为key-value 1.2 数据存储在内存中. 1.2.1 优点:效率高.理论值:每秒1 ...
- openstack_swift源代码分析——Swift单机部署
本文对在单机部署swift 当中每个细节做具体的介绍,并对配置做对应的解释 PC物理机 Ubuntu-12.04-desktop-64位 Swift 版本号:1.13.1 Swift-clien ...
- 简易C#动态加载dll(实现插件化)
可以通过该方法来实现程序插件化. 假设A,B两个类,A类为宿主,B类为插件需要加载到A类中: class Program { public interface IHellow { void Hello ...
- OOM问题定位方法
1. 背景 线上内存OOM问题是最难定位的问题,最常见的原因: (1)本身资源不够 (2)申请的太多 (3)资源耗尽 某服务器上部署了Java服务,出现OutOfMemoryError,请问有可能是什 ...
- AngularJS通过$sce输出html的方法
不知道大家有没有发现在用AngularJS作为前端搭建个人博客的时候,发现用AngularJs输出html的时候,浏览器并不解析这些html标签,这里我们需要其显示angular输出的html能被浏览 ...
- Spring Boot干货系列:(八)数据存储篇-SQL关系型数据库之JdbcTemplate的使用
Spring Boot干货系列:(八)数据存储篇-SQL关系型数据库之JdbcTemplate的使用 原创 2017-04-13 嘟嘟MD 嘟爷java超神学堂 前言 前面几章介绍了一些基础,但都是静 ...