javascript常用函数(2)
文章主要内容列表:
16、 除去数组重复项
17、 操作cookie
18、 判断浏览器类型
19、 判断是否开启cookie
20、 断是否开启JavaScript
21、 JavaScript 打字机效果
22、 简单打印
23、 禁止右键
24、 防止垃圾邮件
25、复制(javaeye flash版)
26、 阻止冒泡事件或阻止浏览器默认行为
27、 关闭或跳转窗口时提示
28、 用javascript获取地 址栏参数
29、 计算停留的时间
30、 div为空,只有背景时,背景自动增高
主要内容:
16、除去数组重复项
<script> Array.prototype.remove = function(){ var $ = this; var o1 = {}; var o2 = {}; var o3 = []; var o; for(var i=0;o = $[i];i++){ if(o in o1){ if(!(o in o2)) o2[o] = o; delete $[i]; }else{ o1[o] = o; } } $.length = 0; for(o in o1){ $.push(o); } for(o in o2){ o3.push(o); } return o3; } var a = [2,2,2,3,3,3,4,4,5,6,7,7]; a.remove (); document.write(a); </script>
17、 操作cookie
// 1. 设置COOKIE // 简单型 function setCookie(c_name,value,expiredays) { var exdate=new Date() exdate.setDate(exdate.getDate()+expiredays) document.cookie=c_name+ "=" +escape(value)+ ((expiredays==null) ? "" : ";expires="+exdate.toGMTString()) } // 完整型 function SetCookie(name,value,expires,path,domain,secure) { var expDays = expires*24*60*60*1000; var expDate = new Date(); expDate.setTime(expDate.getTime()+expDays); var expString = ((expires==null) ? "" : (";expires=”+expDate.toGMTString())) var pathString = ((path==null) ? "" : (";path="+path)) var domainString = ((domain==null) ? "" : (";domain="+domain)) var secureString = ((secure==true) ? ";secure" : "" ) document.cookie = name + "=" + escape(value) + expString + pathString + domainString + secureString; } // 2.获取指定名称的cookie值: function getCookie(c_name) { if (document.cookie.length>0) { c_start=document.cookie.indexOf(c_name + "=") if (c_start!=-1) { c_start=c_start + c_name.length+1 c_end=document.cookie.indexOf(";",c_start) if (c_end==-1) c_end=document.cookie.length return unescape(document.cookie.substring(c_start,c_end)) } } return "" } // 3.删除指定名称的cookie: function ClearCookie(name) { var expDate = new Date(); expDate.setTime(expDate.getTime()-100); document.cookie=name+”=;expires=”+expDate.toGMTString(); } // 4. 检测cookie: function checkCookie() { username=getCookie('username') if (username!=null && username!="") {alert('Welcome again '+username+'!')} else { username=prompt('Please enter your name:',"") if (username!=null && username!="") { setCookie('username',username,365) } } }
18、获取坐标
<!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>payment</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <body style="font-size:12px;"> <script> var strInfo=""; strInfo += "网页可见区域宽:" + document.body.clientWidth + "<br>"; strInfo += "网页可见区域高:" + document.body.clientHeight + "<br>"; strInfo += "网页可见区域宽:" + document.body.offsetWidth + "(包括边线的宽)<br>"; strInfo += "网页可见区域高:" + document.body.offsetHeight + "(包括边线的宽)<br>"; strInfo += "网页正文全文宽:" + document.body.scrollWidth + "<br>"; strInfo += "网页正文全文高:" + document.body.scrollHeight + "<br>"; strInfo += "网页被卷去的高:" + document.body.scrollTop + "<br>"; strInfo += "网页被卷去的左:" + document.body.scrollLeft + "<br>"; strInfo += "网页正文部分上:" + window.screenTop + "<br>"; strInfo += "网页正文部分左:" + window.screenLeft + "<br>"; strInfo += "屏幕分辨率的高:" + window.screen.height + "<br>"; strInfo += "屏幕分辨率的宽:" + window.screen.width + "<br>"; strInfo += "屏幕可用工作区高度:" + window.screen.availHeight + "<br>"; strInfo += "屏幕可用工作区宽度:" + window.screen.availWidth + "<br>"; document.write(strInfo); </script> <br><br> <p> clientX 设置或获取鼠标指针位置相对于窗口客户区域的 x 坐标,其中客户区域不包括窗口自身的控件和滚动条。 <br> clientY 设置或获取鼠标指针位置相对于窗口客户区域的 y 坐标,其中客户区域不包括窗口自身的控件和滚动条。<br> offsetX 设置或获取鼠标指针位置相对于触发事件的对象的 x 坐标。<br> offsetY 设置或获取鼠标指针位置相对于触发事件的对象的 y 坐标。<br> screenX 设置或获取获取鼠标指针位置相对于用户屏幕的 x 坐标。<br> screenY 设置或获取鼠标指针位置相对于用户屏幕的 y 坐标。<br> x 设置或获取鼠标指针位置相对于父文档的 x 像素坐标。<br> y 设置或获取鼠标指针位置相对于父文档的 y 像素坐标。<br> event.clientX返回事件发生时,mouse相对于客户窗口的X坐标,event.X也一样。<br> 但是如果设置事件对象的定位属性值为relative,event.clientX不变,而event.X返回事件对象的相对于本体的坐标。<br> </p> </body> </html>
18、 判断浏览器类型
Js代码
<script type="text/javascript"> var Sys = {}; var ua = navigator.userAgent.toLowerCase(); var s; (s = ua.match(/msie ([\d.]+)/)) ? Sys.ie = s[1] : (s = ua.match(/firefox\/([\d.]+)/)) ? Sys.firefox = s[1] : (s = ua.match(/chrome\/([\d.]+)/)) ? Sys.chrome = s[1] : (s = ua.match(/opera.([\d.]+)/)) ? Sys.opera = s[1] : (s = ua.match(/version\/([\d.]+).*safari/)) ? Sys.safari = s[1] : 0; //以下进行测试 if (Sys.ie) document.write('IE: ' + Sys.ie); if (Sys.firefox) document.write('Firefox: ' + Sys.firefox); if (Sys.chrome) document.write('Chrome: ' + Sys.chrome); if (Sys.opera) document.write('Opera: ' + Sys.opera); if (Sys.safari) document.write('Safari: ' + Sys.safari); </script>
jquery版
<script src="jquery-latest.js"></script> <script type="text/javascript"> $(document).ready(function(){ var bro=$.browser; var binfo=""; if(bro.msie) {binfo="Microsoft Internet Explorer "+bro.version;} if(bro.mozilla) {binfo="Mozilla Firefox "+bro.version;} if(bro.safari) {binfo="Apple Safari "+bro.version;} if(bro.opera) {binfo="Opera "+bro.version;} alert(binfo); }) </script>
19、判断是否开启cookie
<script> function checkCookie() { var result=false; if(navigator.cookiesEnabled){ return true; } document.cookie = "testcookie=yes;"; var setCookie = document.cookie; if (setCookie.indexOf("testcookie=yes") > -1){ result=true; }else{ document.cookie = ""; } return result; } if(!checkCookie()){ alert("对不起,您的浏览器的Cookie功能被禁用,请开启"); }else{ alert("Cookie 成功开启"); } </script>
20、 断是否开启JavaScript
// 方案 1 <span id="js_enable">您关闭了JavaScript</span> <script type="text/javascript"> <!-- document.getElementById("js_enable").innerHTML='您开启了JavaScript'; --> </script> // 方案 2 <div id="NoJs" >您禁用了javascript。</div> <div id="YesJs" style="display:none;">您的Javascript是开启的</div> <script> var NoJs= document.getElementById("NoJs"); var YesJs= document.getElementById("YesJs"); NoJs.style.display="none"; YesJs.style.display="block"; </script> // 方案 3 <!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>检查浏览器是否开启JavaScript</title> </head> <body> 如果您的浏览器支持的话,本页面什么也不会显示,如果不支持,则会出现提示! <noscript> <body scroll=no style="text-align: center"> <center> <table border="0" style="height: 100%; width: 100%; right: 1%; left: 1%; background: black; position: fixed"> <tr> <td align="center"> <div style="position: fixed; font-size: 18px; z-index: 2; cursor: help; background: #F8F8FF; width: 480px; color: black; padding: 5px 5px 5px 5px; border: 1px solid; border-color: maroon; height: auto; text-align: left; left: 20%"> <span style="font: bold 20px Arial; color:#F8F8FF; background: maroon; vertical-align: middle">对不起,你的浏览器没有打开JavaScript脚本支持!</span></div> </td> </tr> </table> </center> </noscript> </body> </html>
HTML <noscript> 标签
定义和用法 noscript 元素用来定义在脚本未被执行时的替代内容(文本)。
此标签可被用于可识别 <script> 标签但无法支持其中的脚本的浏览器。
注释:如果浏览器支持脚本,那么它不会显示出 noscript 元素中的文本。
注释:无法识别 <script> 标签的浏览器会把标签的内容显示到页面上。为了避免浏览器这样做,您应当在注释标签中隐藏脚本。老式的(无法识别 <script> 标签的)浏览器会忽略注释,这样就不会把标签的内容写到页面上,而新式的浏览器则懂得执行这些脚本,即使它们被包围在注释标签中!
21、JavaScript 打字机效果
实例1
<html> <title>JavaScript 打字机</title> <head> <style type="text/css"> body{ font-family: Trebuchet MS, Lucida Sans Unicode, Arial, sans-serif; margin-top:0px; background-image:url('../../images/heading3.gif'); background-repeat:no-repeat; padding-top:100px; } #myContent, #myContent blink{ width:500px; height:200px; background:black; color: #00FF00; font-family:courier; } blink{ display:inline; } </style> <script type="text/javascript"> var charIndex = -1; var stringLength = 0; var inputText; function writeContent(init){ if(init){ inputText = document.getElementById('contentToWrite').innerHTML; } if(charIndex==-1){ charIndex = 0; stringLength = inputText.length; } var initString = document.getElementById('myContent').innerHTML; initStringinitString = initString.replace(/<SPAN.*$/gi,""); var theChar = inputText.charAt(charIndex); var nextFourChars = inputText.substr(charIndex,4); if(nextFourChars=='<BR>' || nextFourChars=='<br>'){ theChar = '<BR>'; charIndex+=3; } initStringinitString = initString + theChar + "<SPAN id='blink'>_</SPAN>"; document.getElementById('myContent').innerHTML = initString; charIndexcharIndex = charIndex/1 +1; if(charIndex%2==1){ document.getElementById('blink').style.display='none'; }else{ document.getElementById('blink').style.display='inline'; } if(charIndex<=stringLength){ setTimeout('writeContent(false)',150); }else{ blinkSpan(); } } var currentStyle = 'inline'; function blinkSpan(){ if(currentStyle=='inline'){ currentStyle='none'; }else{ currentStyle='inline'; } document.getElementById('blink').style.display = currentStyle; setTimeout('blinkSpan()',500); } </script> <body> <div id="myContent"> </div> <div id="contentToWrite" style="display:none"> <!-- Put the typewriter content here--> sharejs.com Login : username<br> password : ******<br> Access is granted<br> <!-- End typewriter content --> </div> <script type="text/javascript"> writeContent(true); </script> </body> </html>
实例2 (兼容IE,FX)
<html> <head> <title>打字效果的带链接的新闻标题</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <style type="text/css"> body{font-size:14px;font-weight:bold;} </style> </head> <body> 最新内容:<a id="HotNews" href="" target="_blank"></a> <script language="JavaScript"> var NewsTime = 2000; //每条新闻的停留时间 var TextTime = 50; //新闻标题文字出现等待时间,越小越快 var newsi = 0; var txti = 0; var txttimer; var newstimer; var newnewstitle = new Array(); //新闻标题 var newnewshref = new Array(); //新闻链接 newstitle[0] = "javascript常用函数"; newshref[0] = "http://www.jb51.net/article/74365.htm"; newstitle[1] = "http://www.jb51.net/"; newshref[1] = "http://www.jb51.net/"; function shownew() { var endstr = "_"; hwnewstr = newstitle[newsi]; newslink = newshref[newsi]; if(txti==(hwnewstr.length-1)){endstr="";} if(txti>=hwnewstr.length){ clearInterval(txttimer); clearInterval(newstimer); newsi++; if(newsi>=newstitle.length){ newsi = 0 } newstimer = setInterval("shownew()",NewsTime); txti = 0; return; } clearInterval(txttimer); document.getElementById("HotNews").href=newslink; document.getElementById("HotNews").innerHTML = hwnewstr.substring(0,txti+1)+endstr; txti++; txttimer = setInterval("shownew()",TextTime); } shownew(); </script> </body> </html>
22、简单打印
<style type="text/css" media=print> .noprint{display : none } </style> <input id="btnPrint" type="button" value="打印" onclick="javascript:window.print();" /><br> 这里是被打印的地方,这里是被打印的地方,这里是被打印的地方,这里是被打印的地方,这里是被打印的地方,<br> 这里是被打印的地方,这里是被打印的地方,这里是被打印的地方,这里是被打印的地方,这里是被打印的地方,<br> 这里是被打印的地方,这里是被打印的地方,这里是被打印的地方,这里是被打印的地方,这里是被打印的地方,<br> <p class="noprint">这里是不需要打印的地方</p>
23、禁止右键
<html> <title>jquery 禁止右键</title> <head> <script src="jquery.js"></script> <script type="text/javascript"> $(function(){ $(document).bind("contextmenu",function(e){ return false; }); }); </script> <body> Xinjiang to implement amended public security measures to safeguard social stability Xinjiang to implement amended public security measures to safeguard social stability Xinjiang to implement amended public security measures to safeguard social stability Xinjiang to implement amended public security measures to safeguard social stability Xinjiang to implement amended public security measures to safeguard social stability Xinjiang to implement amended public security measures to safeguard social stability </body> </html>
24、防止垃圾邮件
<script language="JavaScript"> var rJJdg="PYRUq"; var vjenFG="@cef.com"; var syniH="deo"; // 邮箱名字 var nQEEGoTp="@Deographics.com"; // 邮箱后缀 var KnJbiFO="imLCHy"; var JTCRe="@GZeejp.com"; var NersngGn=2014; // 邮箱地址loading时间 setTimeout("GRUBeoQUurKVgk()",NersngGn); function GRUBeoQUurKVgk(){ document.getElementById("TPNTZyRk").href= "mailto:"+syniH + nQEEGoTp; document.getElementById("gTslyYgEq").innerHTML = syniH + nQEEGoTp; } </script> <a id=TPNTZyRk><span id="gTslyYgEq">Email Loading...</span></a> <span style=display:none;>JwcFoxtWH@aPpeoOw.com RPibMejAUX@NQDg.com PWlVlgKG@QCpBcER.com SxOuqrHes@mszff.com taMmRPLu@EzcI.com NfXidnW@yympz.com quuMcbaKda@aUNdsyb.com DcnXCxaR@QcrN.com QeofXl@ibCh.com OxqzDkSH@hrScW.com</span>
25、复制(javaeye flash版)
<?php $clipboard = "This is a test !!"; ?> <div class="tools"> Javaeye <embed tplayername="SWF" splayername="SWF" id="Player1264100331386" type="application/x-shockwave-flash" src="clipboard.swf" mediawrapchecked="true" flashvars="clipboard=<?=$clipboard?>" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer" height="15" width="14"> <div><textarea id="blog_content"><?=$clipboard?></textarea></div> </div>
26、阻止冒泡事件或阻止浏览器默认行为
//阻止冒泡事件 function stopBubble(e) { if (e && e.stopPropagation) {//非IE e.stopPropagation(); } else {//IE window.event.cancelBubble = true; } } function stopDefault(e) { //阻止默认浏览器动作(W3C) if (e && e.preventDefault) e.preventDefault(); //IE中阻止函数器默认动作的方式 else window.event.returnValue = false; return false; }
27、关闭或跳转窗口时提示
<script language="javascript"> function IsClose() { if(confirm("是否退出系统?")) { return true; } return false; } </script> <body onbeforeunload="javascript:if(IsClose()){return false;}else{return true}"> -------------------------------------------------------- </body> 或者 <script> function winclose(){ return '是否退出系统?'; } </script> <body onbeforeunload="return winclose()" > </body>
28、用javascript获取地 址栏参数
//本页地址为: alert(document.location);
方法一:
<script type="text/javascript"> <!-- String.prototype.getQuery = function(name) { var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); var r = this.substr(this.indexOf("\?")+1).match(reg); if (r!=null) return unescape(r[2]); return null; } var strHref = "www.cnlei.org/index.htm?a=aaa&b=bbb&c=ccc"; alert(strHref.getQuery("a")); alert(strHref.getQuery("b")); alert(strHref.getQuery("c")); //--> </script>
方法二:
<script type="text/javascript"> function getUrlPara(paraName){ var sUrl = location.href; var sReg = "(?:\\?|&){1}"+paraName+"=([^&]*)" var re=new RegExp(sReg,"gi"); re.exec(sUrl); return RegExp.$1; } //应用实例:test_para.html?a=11&b=22&c=33 alert(getUrlPara("a")); alert(getUrlPara("b")); </script>
方法三:
<script type="text/javascript"> <!-- function Request(strName){ var strHref = "www.cnlei.org/index.htm?a=aaa&b=bbb&c=ccc"; var intPos = strHref.indexOf("?"); var strRight = strHref.substr(intPos + 1); var arrTmp = strRight.split("&"); for(var i = 0; i < arrTmp.length; i++) { var arrTemp = arrTmp[i].split("="); if(arrTemp[0].toUpperCase() == strName.toUpperCase()) return arrTemp[1]; } return ""; } alert(Request("a")); alert(Request("b")); alert(Request("c")); //--> </script>
29、计算停留的时间
<html> <form name="myform"> <td vAlign="top" width="135">您在此停留了: <input name="clock" size="8" value="在线时间"></td> </form> <script language="JavaScript"> var id, iM = 0, iS = 1; start = new Date(); function go(){ now = new Date(); time = (now.getTime() - start.getTime()) / 1000; time = Math.floor( time); iS = time % 60; iM = Math.floor( time / 60); if ( iS < 10) document.myform.clock.value = " " + iM + " 分 0" + iS + " 秒"; else document.myform.clock.value = " " + iM + " 分 " + iS + " 秒"; id = setTimeout( "go()", 1000); } go(); </script> </body> </html>
30、div为空,只有背景时,背景自动增高
<script src="jquery-latest.js"></script> <script> $(function(){ var $height = $('#main').height(); // main 是主体自动增高的 id $('#bg').css('height',$height); // bg 是随主体自动增高的无内容背景div的id,一般是阴影之类的 }) </script>
iframe 版
<iframe src="iframe_b.html" scrolling="no" frameborder="0" width="100%" onload="this.height=this.contentWindow.document.documentElement.scrollHeight"></iframe>
以上就是小编为大家整理的常用的javascript函数,希望对大家的学习有所帮助,还有最后一篇关于常用的javascript函数的文章即将推出,继续关注。