javascript常用函数(2)
文章主要内容列表:
16、除去数组重复项
17、操作cookie
18、判断浏览器类型
19、判断是否开启cookie
20、断是否开启JavaScript
21、JavaScript打字机效果
22、简单打印
23、禁止右键
24、防止垃圾邮件
25、复制(javaeyeflash版)
26、阻止冒泡事件或阻止浏览器默认行为
27、关闭或跳转窗口时提示
28、用javascript获取地址栏参数
29、计算停留的时间
30、div为空,只有背景时,背景自动增高
主要内容:
16、除去数组重复项
<script>
Array.prototype.remove=function(){
var$=this;
varo1={};
varo2={};
varo3=[];
varo;
for(vari=0;o=$[i];i++){
if(oino1){
if(!(oino2))o2[o]=o;
delete$[i];
}else{
o1[o]=o;
}
}
$.length=0;
for(oino1){
$.push(o);
}
for(oino2){
o3.push(o);
}
returno3;
}
vara=[2,2,2,3,3,3,4,4,5,6,7,7];
a.remove();
document.write(a);
</script>
17、操作cookie
//1.设置COOKIE
//简单型
functionsetCookie(c_name,value,expiredays)
{
varexdate=newDate()
exdate.setDate(exdate.getDate()+expiredays)
document.cookie=c_name+"="+escape(value)+
((expiredays==null)?"":";expires="+exdate.toGMTString())
}
//完整型
functionSetCookie(name,value,expires,path,domain,secure)
{
varexpDays=expires*24*60*60*1000;
varexpDate=newDate();
expDate.setTime(expDate.getTime()+expDays);
varexpString=((expires==null)?"":(";expires=”+expDate.toGMTString()))
varpathString=((path==null)?"":(";path="+path))
vardomainString=((domain==null)?"":(";domain="+domain))
varsecureString=((secure==true)?";secure":"")
document.cookie=name+"="+escape(value)+expString+pathString+domainString+secureString;
}
//2.获取指定名称的cookie值:
functiongetCookie(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
returnunescape(document.cookie.substring(c_start,c_end))
}
}
return""
}
//3.删除指定名称的cookie:
functionClearCookie(name)
{
varexpDate=newDate();
expDate.setTime(expDate.getTime()-100);
document.cookie=name+”=;expires=”+expDate.toGMTString();
}
//4.检测cookie:
functioncheckCookie()
{
username=getCookie('username')
if(username!=null&&username!="")
{alert('Welcomeagain'+username+'!')}
else
{
username=prompt('Pleaseenteryourname:',"")
if(username!=null&&username!="")
{
setCookie('username',username,365)
}
}
}
18、获取坐标
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <htmlxmlns="http://www.w3.org/1999/xhtml"> <head> <title>payment</title> <metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/> </head> <bodystyle="font-size:12px;"> <script> varstrInfo=""; 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代码
<scripttype="text/javascript">
varSys={};
varua=navigator.userAgent.toLowerCase();
vars;
(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版
<scriptsrc="jquery-latest.js"></script>
<scripttype="text/javascript">
$(document).ready(function(){
varbro=$.browser;
varbinfo="";
if(bro.msie){binfo="MicrosoftInternetExplorer"+bro.version;}
if(bro.mozilla){binfo="MozillaFirefox"+bro.version;}
if(bro.safari){binfo="AppleSafari"+bro.version;}
if(bro.opera){binfo="Opera"+bro.version;}
alert(binfo);
})
</script>
19、判断是否开启cookie
<script>
functioncheckCookie(){
varresult=false;
if(navigator.cookiesEnabled){returntrue;}
document.cookie="testcookie=yes;";
varsetCookie=document.cookie;
if(setCookie.indexOf("testcookie=yes")>-1){
result=true;
}else{
document.cookie="";
}
returnresult;
}
if(!checkCookie()){
alert("对不起,您的浏览器的Cookie功能被禁用,请开启");
}else{
alert("Cookie成功开启");
}
</script>
20、断是否开启JavaScript
//方案1
<spanid="js_enable">您关闭了JavaScript</span>
<scripttype="text/javascript">
<!--
document.getElementById("js_enable").innerHTML='您开启了JavaScript';
-->
</script>
//方案2
<divid="NoJs">您禁用了javascript。</div>
<divid="YesJs"style="display:none;">您的Javascript是开启的</div>
<script>
varNoJs=document.getElementById("NoJs");
varYesJs=document.getElementById("YesJs");
NoJs.style.display="none";
YesJs.style.display="block";
</script>
//方案3
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/>
<title>检查浏览器是否开启JavaScript</title>
</head>
<body>
如果您的浏览器支持的话,本页面什么也不会显示,如果不支持,则会出现提示!
<noscript>
<bodyscroll=nostyle="text-align:center">
<center>
<tableborder="0"style="height:100%;width:100%;right:1%;left:1%;background:black;position:fixed">
<tr>
<tdalign="center">
<divstyle="position:fixed;font-size:18px;z-index:2;cursor:help;background:#F8F8FF;width:480px;color:black;padding:5px5px5px5px;border:1pxsolid;border-color:maroon;height:auto;text-align:left;left:20%">
<spanstyle="font:bold20pxArial;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>
<styletype="text/css">
body{
font-family:TrebuchetMS,LucidaSansUnicode,Arial,sans-serif;
margin-top:0px;
background-image:url('../../images/heading3.gif');
background-repeat:no-repeat;
padding-top:100px;
}
#myContent,#myContentblink{
width:500px;
height:200px;
background:black;
color:#00FF00;
font-family:courier;
}
blink{
display:inline;
}
</style>
<scripttype="text/javascript">
varcharIndex=-1;
varstringLength=0;
varinputText;
functionwriteContent(init){
if(init){
inputText=document.getElementById('contentToWrite').innerHTML;
}
if(charIndex==-1){
charIndex=0;
stringLength=inputText.length;
}
varinitString=document.getElementById('myContent').innerHTML;
initStringinitString=initString.replace(/<SPAN.*$/gi,"");
vartheChar=inputText.charAt(charIndex);
varnextFourChars=inputText.substr(charIndex,4);
if(nextFourChars=='<BR>'||nextFourChars=='<br>'){
theChar='<BR>';
charIndex+=3;
}
initStringinitString=initString+theChar+"<SPANid='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();
}
}
varcurrentStyle='inline';
functionblinkSpan(){
if(currentStyle=='inline'){
currentStyle='none';
}else{
currentStyle='inline';
}
document.getElementById('blink').style.display=currentStyle;
setTimeout('blinkSpan()',500);
}
</script>
<body>
<divid="myContent">
</div>
<divid="contentToWrite"style="display:none">
<!--Putthetypewritercontenthere-->
sharejs.com
Login:username<br>
password:******<br>
Accessisgranted<br>
<!--Endtypewritercontent-->
</div>
<scripttype="text/javascript">
writeContent(true);
</script>
</body>
</html>
实例2(兼容IE,FX)
<html>
<head>
<title>打字效果的带链接的新闻标题</title>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<styletype="text/css">
body{font-size:14px;font-weight:bold;}
</style>
</head>
<body>
最新内容:<aid="HotNews"href=""target="_blank"></a>
<scriptlanguage="JavaScript">
varNewsTime=2000;//每条新闻的停留时间
varTextTime=50;//新闻标题文字出现等待时间,越小越快
varnewsi=0;
vartxti=0;
vartxttimer;
varnewstimer;
varnewnewstitle=newArray();//新闻标题
varnewnewshref=newArray();//新闻链接
newstitle[0]="javascript常用函数";
newshref[0]="https://www.nhooo.com/article/74365.htm";
newstitle[1]="https://www.nhooo.com/";
newshref[1]="https://www.nhooo.com/";
functionshownew()
{
varendstr="_";
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、简单打印
<styletype="text/css"media=print>
.noprint{display:none}
</style>
<inputid="btnPrint"type="button"value="打印"onclick="javascript:window.print();"/><br>
这里是被打印的地方,这里是被打印的地方,这里是被打印的地方,这里是被打印的地方,这里是被打印的地方,<br>
这里是被打印的地方,这里是被打印的地方,这里是被打印的地方,这里是被打印的地方,这里是被打印的地方,<br>
这里是被打印的地方,这里是被打印的地方,这里是被打印的地方,这里是被打印的地方,这里是被打印的地方,<br>
<pclass="noprint">这里是不需要打印的地方</p>
23、禁止右键
<html>
<title>jquery禁止右键</title>
<head>
<scriptsrc="jquery.js"></script>
<scripttype="text/javascript">
$(function(){
$(document).bind("contextmenu",function(e){
returnfalse;
});
});
</script>
<body>
Xinjiangtoimplementamendedpublicsecuritymeasurestosafeguardsocialstability
Xinjiangtoimplementamendedpublicsecuritymeasurestosafeguardsocialstability
Xinjiangtoimplementamendedpublicsecuritymeasurestosafeguardsocialstability
Xinjiangtoimplementamendedpublicsecuritymeasurestosafeguardsocialstability
Xinjiangtoimplementamendedpublicsecuritymeasurestosafeguardsocialstability
Xinjiangtoimplementamendedpublicsecuritymeasurestosafeguardsocialstability
</body>
</html>
24、防止垃圾邮件
<scriptlanguage="JavaScript">
varrJJdg="PYRUq";
varvjenFG="@cef.com";
varsyniH="deo";//邮箱名字
varnQEEGoTp="@Deographics.com";//邮箱后缀
varKnJbiFO="imLCHy";
varJTCRe="@GZeejp.com";
varNersngGn=2014;//邮箱地址loading时间
setTimeout("GRUBeoQUurKVgk()",NersngGn);
functionGRUBeoQUurKVgk(){
document.getElementById("TPNTZyRk").href="mailto:"+syniH+nQEEGoTp;
document.getElementById("gTslyYgEq").innerHTML=syniH+nQEEGoTp;
}
</script>
<aid=TPNTZyRk><spanid="gTslyYgEq">EmailLoading...</span></a>
<spanstyle=display:none;>JwcFoxtWH@aPpeoOw.comRPibMejAUX@NQDg.comPWlVlgKG@QCpBcER.comSxOuqrHes@mszff.comtaMmRPLu@EzcI.comNfXidnW@yympz.comquuMcbaKda@aUNdsyb.comDcnXCxaR@QcrN.comQeofXl@ibCh.comOxqzDkSH@hrScW.com</span>
25、复制(javaeyeflash版)
<?php $clipboard="Thisisatest!!"; ?> <divclass="tools"> Javaeye <embedtplayername="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><textareaid="blog_content"><?=$clipboard?></textarea></div> </div>
26、阻止冒泡事件或阻止浏览器默认行为
//阻止冒泡事件
functionstopBubble(e){
if(e&&e.stopPropagation){//非IE
e.stopPropagation();
}
else{//IE
window.event.cancelBubble=true;
}
}
functionstopDefault(e){
//阻止默认浏览器动作(W3C)
if(e&&e.preventDefault)
e.preventDefault();
//IE中阻止函数器默认动作的方式
else
window.event.returnValue=false;
returnfalse;
}
27、关闭或跳转窗口时提示
<scriptlanguage="javascript">
functionIsClose()
{
if(confirm("是否退出系统?"))
{
returntrue;
}
returnfalse;
}
</script>
<bodyonbeforeunload="javascript:if(IsClose()){returnfalse;}else{returntrue}">
--------------------------------------------------------
</body>
或者
<script>
functionwinclose(){
return'是否退出系统?';
}
</script>
<bodyonbeforeunload="returnwinclose()">
</body>
28、用javascript获取地址栏参数
//本页地址为: alert(document.location);
方法一:
<scripttype="text/javascript">
<!--
String.prototype.getQuery=function(name){
varreg=newRegExp("(^|&)"+name+"=([^&]*)(&|$)");
varr=this.substr(this.indexOf("\?")+1).match(reg);
if(r!=null)returnunescape(r[2]);returnnull;
}
varstrHref="www.cnlei.org/index.htm?a=aaa&b=bbb&c=ccc";
alert(strHref.getQuery("a"));
alert(strHref.getQuery("b"));
alert(strHref.getQuery("c"));
//-->
</script>
方法二:
<scripttype="text/javascript">
functiongetUrlPara(paraName){
varsUrl=location.href;
varsReg="(?:\\?|&){1}"+paraName+"=([^&]*)"
varre=newRegExp(sReg,"gi");
re.exec(sUrl);
returnRegExp.$1;
}
//应用实例:test_para.html?a=11&b=22&c=33
alert(getUrlPara("a"));
alert(getUrlPara("b"));
</script>
方法三:
<scripttype="text/javascript">
<!--
functionRequest(strName){
varstrHref="www.cnlei.org/index.htm?a=aaa&b=bbb&c=ccc";
varintPos=strHref.indexOf("?");
varstrRight=strHref.substr(intPos+1);
vararrTmp=strRight.split("&");
for(vari=0;i<arrTmp.length;i++){
vararrTemp=arrTmp[i].split("=");
if(arrTemp[0].toUpperCase()==strName.toUpperCase())returnarrTemp[1];
}
return"";
}
alert(Request("a"));
alert(Request("b"));
alert(Request("c"));
//-->
</script>
29、计算停留的时间
<html>
<formname="myform">
<tdvAlign="top"width="135">您在此停留了:
<inputname="clock"size="8"value="在线时间"></td>
</form>
<scriptlanguage="JavaScript">
varid,iM=0,iS=1;
start=newDate();
functiongo(){
now=newDate();
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为空,只有背景时,背景自动增高
<scriptsrc="jquery-latest.js"></script>
<script>
$(function(){
var$height=$('#main').height();//main是主体自动增高的id
$('#bg').css('height',$height);//bg是随主体自动增高的无内容背景div的id,一般是阴影之类的
})
</script>
iframe版
<iframesrc="iframe_b.html"scrolling="no"frameborder="0"width="100%"onload="this.height=this.contentWindow.document.documentElement.scrollHeight"></iframe>
以上就是小编为大家整理的常用的javascript函数,希望对大家的学习有所帮助,还有最后一篇关于常用的javascript函数的文章即将推出,继续关注。