常用JavaScript函数 59 - 70(自我总结)
59、 展开收缩文章
60、 页面不被框架
61、 验证密码
62、 文字横向滚动
63、 单击button或空白区都隐藏层
64、javascript删除元素节点
65、getElementsByClassName
66、JavaScript验证URL正则
67、背景高亮
68、点击链接滑动 Smooth Scrolling
69、制造文字闪动效果
70、电子时钟 javascript date time clock
59、 展开收缩文章
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>带缓冲的内容展开收缩效果</title> <meta http-equiv="content-type" content="text/html;charset=utf-8"> <!--把下面代码加到<head>与</head>之间--> <style type="text/css"> .main{ float:left; width:500px; margin:4px; padding:4px; line-height:150%; border:1px solid #09c; } .content{ width:100%; height:170px; overflow:hidden; } .c1{ height:170px; } .c2{ height:408px; } .main span.button{ float:right; height:20px; border:#09c 1px solid; margin-left:20px; padding:2px 4px; background-color:#f3f8f7; font-size:12px; cursor:pointer; } </style> <script type="text/javascript"> function senfe(e) { var s = 1.2; var s2 = 8; var obj = e.parentNode; var oh = parseInt(obj.offsetHeight); var h = parseInt(obj.scrollHeight); var nh = oh; if(obj.getAttribute("oldHeight") == null) obj.setAttribute("oldHeight", oh); else var oldh = Math.ceil(obj.getAttribute("oldHeight")); var reSet = function(){ if (oh<h) { e.innerHTML = "关 闭"; if(nh < h){ nh = Math.ceil(h-(h-nh)/s); obj.style.height = nh+"px"; } else window.clearInterval(IntervalId); } else { e.innerHTML = "展 开"; if(nh > oldh){ nhh = Math.ceil((nh-oldh)/s2); nh = nh-nhh; obj.style.height = nh+"px"; } else window.clearInterval(IntervalId); } } var IntervalId = window.setInterval(reSet,10); } </script> </head> <body> <div class="main"> <div class="content"> <span class="button" onclick="senfe(this);">展 开</span> 这是一款带缓冲的内容展开收缩效果的js代码,它很好的搞出一拉伸效果的div css显示下拉效果fdsafdsafdsaf 这是一款带缓冲的内容展开收缩效果的js代码,它很好的搞出一拉伸效果的div css显示下拉效果fdsafdsafdsaf 这是一款带缓冲的内容展开收缩效果的js代码,它很好的搞出一拉伸效果的div css显示下拉效果fdsafdsafdsaf 这是一款带缓冲的内容展开收缩效果的js代码,它很好的搞出一拉伸效果的div css显示下拉效果fdsafdsafdsaf 这是一款带缓冲的内容展开收缩效果的js代码,它很好的搞出一拉伸效果的div css显示下拉效果fdsafdsafdsaf 这是一款带缓冲的内容展开收缩效果的js代码,它很好的搞出一拉伸效果的div css显示下拉效果fdsafdsafdsaf 这是一款带缓冲的内容展开收缩效果的js代码,它很好的搞出一拉伸效果的div css显示下拉效果fdsafdsafdsaf 这是一款带缓冲的内容展开收缩效果的js代码,它很好的搞出一拉伸效果的div css显示下拉效果fdsafdsafdsaf 这是一款带缓冲的内容展开收缩效果的js代码,它很好的搞出一拉伸效果的div css显示下拉效果fdsafdsafdsaf 这是一款带缓冲的内容展开收缩效果的js代码,它很好的搞出一拉伸效果的div css显示下拉效果fdsafdsafdsaf 这是一款带缓冲的内容展开收缩效果的js代码,它很好的搞出一拉伸效果的div css显示下拉效果fdsafdsafdsaf 这是一款带缓冲的内容展开收缩效果的js代码,它很好的搞出一拉伸效果的div css显示下拉效果fdsafdsafdsaf 这是一款带缓冲的内容展开收缩效果的js代码,它很好的搞出一拉伸效果的div css显示下拉效果fdsafdsafdsaf 这是一款带缓冲的内容展开收缩效果的js代码,它很好的搞出一拉伸效果的div css显示下拉效果fdsafdsafdsaf 这是一款带缓冲的内容展开收缩效果的js代码,它很好的搞出一拉伸效果的div css显示下拉效果fdsafdsafdsaf 这是一款带缓冲的内容展开收缩效果的js代码,它很好的搞出一拉伸效果的div css显示下拉效果fdsafdsafdsaf 这是一款带缓冲的内容展开收缩效果的js代码,它很好的搞出一拉伸效果的div css显示下拉效果fdsafdsafdsaf 这是一款带缓冲的内容展开收缩效果的js代码,它很好的搞出一拉伸效果的div css显示下拉效果fdsafdsafdsaf </div> </div> </body> </html>
60、 页面不被框架
<html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>标题页</title> <Script LANGUAGE="JavaScript"> if(self!=top) top.location=self.location; //判断是否是顶层,不是则将当前页设置为顶层 </script> </head> <body> this is a test </body> </html>
61、 验证密码
<script> /* Password Validator 0.1 (c) 2007 Steven Levithan <stevenlevithan.com> MIT License */ function validatePassword (pw, options) { // default options (allows any password) var o = { lower: 0, upper: 0, alpha: 0, /* lower + upper */ numeric: 0, special: 0, length: [0, Infinity], custom: [ /* regexes and/or functions */ ], badWords: [], badSequenceLength: 0, noQwertySequences: false, noSequential: false }; for (var property in options) o[property] = options[property]; var re = { lower: /[a-z]/g, upper: /[A-Z]/g, alpha: /[A-Z]/gi, numeric: /[0-9]/g, special: /[\W_]/g }, rule, i; // enforce min/max length if (pw.length < o.length[0] || pw.length > o.length[1]) return false; // enforce lower/upper/alpha/numeric/special rules for (rule in re) { if ((pw.match(re[rule]) || []).length < o[rule]) return false; } // enforce word ban (case insensitive) for (i = 0; i < o.badWords.length; i++) { if (pw.toLowerCase().indexOf(o.badWords[i].toLowerCase()) > -1) return false; } // enforce the no sequential, identical characters rule if (o.noSequential && /([\S\s])\1/.test(pw)) return false; // enforce alphanumeric/qwerty sequence ban rules if (o.badSequenceLength) { var lower = "abcdefghijklmnopqrstuvwxyz", upper = lower.toUpperCase(), numbers = "0123456789", qwerty = "qwertyuiopasdfghjklzxcvbnm", start = o.badSequenceLength - 1, seq = "_" + pw.slice(0, start); for (i = start; i < pw.length; i++) { seq = seq.slice(1) + pw.charAt(i); if ( lower.indexOf(seq) > -1 || upper.indexOf(seq) > -1 || numbers.indexOf(seq) > -1 || (o.noQwertySequences && qwerty.indexOf(seq) > -1) ) { return false; } } } // enforce custom regex/function rules for (i = 0; i < o.custom.length; i++) { rule = o.custom[i]; if (rule instanceof RegExp) { if (!rule.test(pw)) return false; } else if (rule instanceof Function) { if (!rule(pw)) return false; } } // great success! return true; } var options = { length: [8, Infinity], lower: 1, upper: 1, numeric: 1, special: 1, badWords: ["password", "steven", "levithan"], badSequenceLength: 4 }; var password1 = "Woaijava1#"; var password2 = "password#"; var passed1 = validatePassword(password1,options); var passed2 = validatePassword(password2,options); alert(passed1); // passed: true alert(passed2); // passed: false </script>
Here are the validation types supported out of the box. All are optional, which means that all passwords are allowed by default.
Minimum and maximum length.
Minimum n lowercase characters (a–z).
Minimum n uppercase characters (A–Z).
Minimum n combined a–z and A–Z characters.
Minimum n numeric characters (0–9).
Minimum n special characters (characters other than a–z, A–Z, and 0–9).
Ban particular words (tested case-insensitively).
Ban n-length character sequences (e.g. "abc", "XYZ", or "789", with a sequence length of 3; does not apply to special characters).
Ban n-length qwerty character sequences (e.g. "qwerty" or "asdf", with a sequence length of 4; does not apply to special characters).
Ban sequential, identical characters (e.g. "aa" or "!!").
Use custom regular expressions (tested using RegExp.prototype.test) and functions (the password is provided as the first argument, and a Boolean value is expected in return).
62、 文字横向滚动
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>向左滚动的文字特效JS代码</title> </head> <body> <div id="demo" style="overflow:hidden;height:24px; line-height:24px;width:600px; border:1px solid #666; white-space:nowrap;"> <div id="demo1"> <a href="#">说明: </a> 这个向左滚动的文字特效JS代码比较简洁,代码量很少,你可以扩展一下, 你完全可以在这里定义图片或者图文结合等等形式,这是一个容器。 style="overflow:hidden;height:24px; line-height:24px;width:600px; border:1px solid #666; white-space:nowrap;" 这一段,向左滚动的文字特效需要这一段样式的配合,在这里宽、高、和white-space:nowrap (强制不换行)是必须的。 </div> <div id="demo2"></div> </div> <script style="text/javascript"> var speed=40;//数值越大,速度越慢 var demo2=document.getElementById("demo2"); var demo1=document.getElementById("demo1"); var demo=document.getElementById("demo"); function MarqueeLeft(){ if(demo2.offsetWidth-demo.scrollLeft<=0) demo.scrollLeft-=demo1.offsetWidth; else demo.scrollLeft++; } var MyMar=setInterval(MarqueeLeft,speed); demo.onmouseover=function() {clearInterval(MyMar);} demo.onmouseout=function() {MyMar=setInterval(MarqueeLeft,speed);} </script> </body> </html>
63、 单击button或空白区都隐藏层
$(function() { var ibox = $("#ibox"); //功能:单击button显示层,单击 button 或者 空白区 都隐藏层 $("#ibutton").click(function(event) { event.stopPropagation(); //阻止冒泡 if(ibox.is(":hidden")) ibox.show(); //单击button显示层 else ibox.hide(); //单击button隐藏层 }); //单击空白区隐藏层 $(document).click(function(){$("#ibox").hide();}); });
其他思路:
$('body').not('p').click(function(){});
或者:
$('*:not(body)').click(function() { alert('clicked an item!'); return false; });
64、javascript删除元素节点
<script type="text/javascript"> function removeElement(_element){ var _parentElement = _element.parentNode; if(_parentElement){ _parentElement.removeChild(_element); } } </script> <div><input onclick="removeElement(this)" type="text" value="点击移除该输入框" /></div>
65、getElementsByClassName
<script type="text/javascript"> /* Developed by Robert Nyman, http://www.robertnyman.com Code/licensing: http://code.google.com/p/getelementsbyclassname/ */ var getElementsByClassName = function (className, tag, elm){ if (document.getElementsByClassName) { getElementsByClassName = function (className, tag, elm) { elm = elm || document; var elements = elm.getElementsByClassName(className), nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null, returnElements = [], current; for(var i=0, il=elements.length; i<il; i+=1){ current = elements[i]; if(!nodeName || nodeName.test(current.nodeName)) { returnElements.push(current); } } return returnElements; }; } else if (document.evaluate) { getElementsByClassName = function (className, tag, elm) { tag = tag || "*"; elm = elm || document; var classes = className.split(" "), classesToCheck = "", xhtmlNamespace = "http://www.w3.org/1999/xhtml", namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null, returnElements = [], elements, node; for(var j=0, jl=classes.length; j<jl; j+=1){ classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]"; } try { elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null); } catch (e) { elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null); } while ((node = elements.iterateNext())) { returnElements.push(node); } return returnElements; }; } else { getElementsByClassName = function (className, tag, elm) { tag = tag || "*"; elm = elm || document; var classes = className.split(" "), classesToCheck = [], elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag), current, returnElements = [], match; for(var k=0, kl=classes.length; k<kl; k+=1){ classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)")); } for(var l=0, ll=elements.length; l<ll; l+=1){ current = elements[l]; match = false; for(var m=0, ml=classesToCheck.length; m<ml; m+=1){ match = classesToCheck[m].test(current.className); if (!match) { break; } } if (match) { returnElements.push(current); } } return returnElements; }; } return getElementsByClassName(className, tag, elm); }; </script>
实例:
<select class="input_numbers" id="input_numbers" name="limitedList"> <option value="100">1-100</option> <option value="200">101-200</option> <option value="300">201-300</option> <option value="400">301-400</option> <option value="500">401-500</option> <option value="600">501-600</option> <option value="700">601-700</option> <option value="800">701-800</option> <option value="900">801-900</option> <option value="1000">901-1000</option> </select> <script type="text/javascript"> var elementList = getElementsByClassName("input_numbers"); alert(elementList[0].options.length); alert(elementList.length); </script>
66、JavaScript验证URL正则
<script> function checkURL(url){ if(url) { var strRegex = "^((https|http):\/\/)?" + "(((([0-9]|1[0-9]{2}|[1-9][0-9]|2[0-4][0-9]|25[0-5])[.]{1}){3}([0-9]|1[0-9]{2}|[1-9][0-9]|2[0-4][0-9]|25[0-5]))" // IP形式的URL- 199.194.52.184 + "|" + "([0-9a-zA-Z\u4E00-\u9FA5\uF900-\uFA2D-]+[.]{1})+[a-zA-Z-]+)" // DOMAIN(域名)形式的URL + "(:[0-9]{1,4})?" // 端口- :80 + "((/?)|(/[0-9a-zA-Z_!~*'().;?:@&=+$,%#-]+)+/?)$"; var re = new RegExp(strRegex); //re.test() return re.test(url); } } </script>
67、背景高亮
jQuery.fn.highlight = function () { $(this).each(function () { var el = $(this); $("<div/>") .width(el.outerWidth()) .height(el.outerHeight()) .css({ "position": "absolute", "left": el.offset().left, "top": el.offset().top, "background-color": "#ffff99", "opacity": ".7", "z-index": "9999999" }).appendTo('body').fadeOut(1000).queue(function () { $(this).remove(); }); }); } $("#target").highlight();
测试:http://jsfiddle.net/x2jrU/92/
68、点击链接滑动 Smooth Scrolling
$(function() { $('a[href*=#]:not([href=#])').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') || location.hostname == this.hostname) { var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); if (target.length) { $('html,body').animate({ scrollTop: target.offset().top }, 1000); return false; } } }); });
69、制造文字闪动效果
.sd{color: #000;} .r{color:#F00;} </style> <script language="javascript" src="jquery.min.js"></script> <script> function changecolor(){ $("a.sd").toggleClass('r') } $().ready(function(){ setInterval(function(){ changecolor()},1000) }) </script>
或者
<script language="javascript"> i=0 function changecolor() { $("A.sd").css("color",i==0?"#000":"red"); i==2?i=0:i++ } $().ready(function(){ setInterval(function(){ changecolor()},500) }) </script>
<a class="sd">闪动</a>
70、电子时钟 javascript date time clock
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Display Date and Time in Javascript</title> <script> function date_time(id) { date = new Date; year = date.getFullYear(); month = date.getMonth(); months = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'); d = date.getDate(); day = date.getDay(); days = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'); h = date.getHours(); if(h<10) h = "0"+h; m = date.getMinutes(); if(m<10) m = "0"+m; s = date.getSeconds(); if(s<10) s = "0"+s; result = ''+days[day]+' '+months[month]+' '+d+' '+year+' '+h+':'+m+':'+s; document.getElementById(id).innerHTML = result; setTimeout('date_time("'+id+'");','1000'); return true; } </script> </head> <body> <span id="date_time"></span> <script type="text/javascript">window.onload = date_time('date_time');</script> </body> </html>