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