JavaScript正變得越來越流行,它已經成為前端開發的第一選擇。下面是小編收集的10段實用JavaScript程式碼,基於它們你還可以創造出更強大的JS外掛或功能函式。
1. 判斷日期是否有效
JavaScript中自帶的日期函式還是太過簡單,很難滿足真實專案中對不同日期格式進行解析和判斷的需要。JQuery也有一些第三方庫來使日期相關的處理變得簡單,但有時你可能只需要一個非常簡單的函式,而不想引入一個龐大的第三方庫。這時,你可以使用下面這段日期校驗程式碼,它允許你自定義日期格式並進行日期有效性的校驗。
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]/(userFormat)[0];
// Create an array with month, day and year
// so we know the format order by index
var theFormat = t(delimiter);
// Create array from user date
var theDate = t(delimiter);
function isDate(date, format) {
var m, d, y, i = 0, len = th, f;
for (i; i < len; i++) {
f = format[i];
if (/m/(f)) m = date[i];
if (/d/(f)) d = date[i];
if (/y/(f)) y = date[i];
}
return (
m > 0 && m < 13 &&
y && th === 4 &&
d > 0 &&
// Check if it's a valid day of the month
d <= (new Date(y, m, 0))ate()
);
}
return isDate(theDate, theFormat);
}
使用方法:
下面這個呼叫返回false,因為11月份沒有31天
isValidDate('dd-mm-yyyy', '31/11/2012')
2. 獲取一組元素的最大寬度或高度
下面這個函式,對於需要進行動態排版的開發人員非常有用。
var getMaxHeight = function ($elms) {
var maxHeight = 0;
$(function () {
// In some cases you may want to use outerHeight() instead
var height = $(this)ht();
if (height > maxHeight) {
maxHeight = height;
}
});
return maxHeight;
};
使用方法:
$(elements)ht( getMaxHeight($(elements)) );
3. 高亮文字
有很多JQuery的第三方庫可以實現高亮文字的功能,但我更喜歡用下面這一小段JavaScript程式碼來實現這個功能,它非常短小,而且可以根據我的需要去進行靈活的修改,而且可以自己定義高亮的樣式。下面這兩個函式可以幫助你建立自己的文字高亮外掛。
function highlight(text, words, tag) {
// Default tag if no tag is provided
tag = tag || 'span';
var i, len = th, re;
for (i = 0; i < len; i++) {
// Global regex to highlight all matches
re = new RegExp(words[i], 'g');
if ((text)) {
text = ace(re, '<'+ tag +'>$&');
}
}
return text;
}
你同樣會需要取消高亮的'函式:
function unhighlight(text, tag) {
// Default tag if no tag is provided
tag = tag || 'span';
var re = new RegExp('(<'+ tag +'.+?>|</'+ tag +'>)', 'g');
return ace(re, '');
}
使用方法:
$('p')( highlight(
$('p')(), // the text
['foo', 'bar', 'baz', 'hello world'], // list of words or phrases to highlight
'strong' // custom tag
));
4. 文字動效
有時你會希望給你的一段文字增加動效,讓其中的每個字都動起來。你可以使用下面這段jQuery外掛程式碼來達到這個效果。當然你需要結合一個CSS3 transition樣式來達到更好的效果。
$ateText = function(delay, klass) {
var text = ();
var letters = t('');
return (function(){
var $this = $(this);
$(ace(/./g, '$&'));
$('er')(function(i, el){
setTimeout(function(){ $(el)lass(klass); }, delay * i);
});
});
};
使用方法:
$('p')ateText(15, 'foo');
5. 逐個隱藏元素
下面這個jQuery外掛可以根據你設定的步長(間隔時間)來逐個隱藏一組元素。在列表元素的重新載入中使用,可以達到很好的效果。