javascript常用函數(shù)(1)
文章主要內(nèi)容列表:
1、 調(diào)整圖片大小,不走形(FF IE 兼容)/ 剪切圖片(overflow:hidden)
2、 控制textarea區(qū)域文字?jǐn)?shù)量
3、 點(diǎn)擊顯示新窗口
4、 input框自動(dòng)隨內(nèi)容自動(dòng)變長(zhǎng)
5、 添加收藏夾
6、 設(shè)置首頁(yè)
7、 Jquery + Ajax 判斷用戶是否存在
8、 判斷email格式是否正確
9、 綜合判斷用戶名(長(zhǎng)度,英文字段等)
10、新聞滾動(dòng)
11、 只允許輸入正整數(shù) (shopping cart 使用) 或者 正數(shù) (正整數(shù)和正小數(shù))
12、 轉(zhuǎn)換字符串為數(shù)字
13、 判斷文件格式(獲得文件后綴)
14、 截取字符串
15、分割字符串
主要內(nèi)容 :
1、 調(diào)整圖片大小,不走形(FF IE 兼容)
// 用法 <img src="this_image_path.jpg" onload="DrawImage(this,450,450);" /> function DrawImage(ImgD,FitWidth,FitHeight){ var image=new Image(); image.src=ImgD.src; if(image.width>0 && image.height>0){ if(image.width/image.height>= FitWidth/FitHeight){ if(image.width>FitWidth){ ImgD.width=FitWidth; ImgD.height=(image.height*FitWidth)/image.width; }else{ ImgD.width=image.width; ImgD.height=image.height; } } else{ if(image.height>FitHeight){ ImgD.height=FitHeight; ImgD.width=(image.width*FitHeight)/image.height; }else{ ImgD.width=image.width; ImgD.height=image.height; } } } }
通過(guò) overflow:hidden進(jìn)行剪切:
function clipImage(o, w, h){ var img = new Image(); img.src = o.src; if(img.width >0 && img.height>0) { if(img.width/img.height >= w/h) { if(img.width > w) { o.width = (img.width*h)/img.height; o.height = h; //o.setAttribute("style", "marginLeft:-" + ((o.width-w)/2).toString() + "px"); $(o).css("margin-left", "-"+((o.width-w)/2).toString() + "px"); } else { o.width = img.width; o.height = img.height; } } else { if(img.height > h) { o.height = (img.height*w)/img.width; o.width = w; //o.setAttribute("style", "margin-top:-" + ((o.height-h)/2).toString() + "px"); //$(o).css("style", "margin-top:-" + ((o.height-h)/2).toString() + "px"); $(o).css("margin-top", "-"+((o.height-h)/2).toString() + "px"); } else { o.width = img.width; o.height = img.height; } } } }
實(shí)例:
<style type="text/css"> ul{list-style:none;} ul li{float:left;padding:1px;border:#ccc 1px solid;width:120px;height:120px;overflow:hidden;text-align:center;over-flow:hidden;} </style> <ul> <li><img src="1.jpg" onload="DrawImage(this,120,120);" /></li> <li><img src="2.jpg" onload="clipImage(this,120,120);" /></li> </ul>
2、控制textarea區(qū)域文字?jǐn)?shù)量
<script> /** * Calculate how many characters remain in a textarea (jQuery) * @param string textarea * @param int maxLength * @param string div */ function charsRemain(textarea, maxLength, div) { var currentLength = $(textarea).val().length; var charsLeft = maxLength - currentLength; if (charsLeft < 0) { charsLeft = 0; } $("#"+ div +"_charsRemain").html(charsLeft); if (currentLength > maxLength) { var fullText = $(textarea).val().substring(0, maxLength); $(textarea).val(fullText); } } /** * Calculate how many characters remain in a textarea (javascript) * @param string textarea * @param int maxLength * @param string div */ function charsRemain(textarea, maxLength, div) { var currentLength = textarea.value.length; var charsLeft = maxLength - currentLength; if (charsLeft < 0) { charsLeft = 0; } document.getElementById(div +"_charsRemain").innerHTML = charsLeft; if (currentLength > maxLength) { var fullText = textarea.value.substring(0, maxLength); textarea.value = fullText; } } </script> <textarea rows="5" cols="15" onkeyup="charsRemain(this, 250, 'textarea');"></textarea> <span id="textarea_charsRemain">250</span> characters remaining
3、點(diǎn)擊顯示新窗口
//彈窗 function g_OpenWindow(pageURL, innerWidth, innerHeight) { var ScreenWidth = screen.availWidth var ScreenHeight = screen.availHeight var StartX = (ScreenWidth - innerWidth) / 2 var StartY = (ScreenHeight - innerHeight) / 2 var wins = window.open(pageURL, 'OpenWin', 'left='+ StartX + ', top='+ StartY + ', Width=' + innerWidth +', height=' + innerHeight + ', resizable=yes, scrollbars=yes, status=no, toolbar=no, menubar=no, location=no') wins.focus(); }
Java代碼 :
<script language="JavaScript"> // 自動(dòng)彈出窗口 var whatsNew = open('','_blank','top=50,left=50,width=200,height=300,' + 'menubar=no,toolbar=no,directories=no,location=no,' + 'status=no,resizable=no,scrollbars=yes'); whatsNew.document.write('<center><b>news</b>< /center>'); whatsNew.document.write('<p>this is a test'); whatsNew.document.write('<p>deos address'); whatsNew.document.write('<p align="right">' + '<a href="javascript:self.close()">Close</a>'); whatsNew.document.close(); </script>
不幸的是,很多瀏覽器會(huì)屏蔽彈出窗口,你需要手動(dòng)允許后方可看到!下面是強(qiáng)制彈出窗口,原理就是創(chuàng)建一個(gè)form,通過(guò)post打開(kāi)。
<script language="javascript"> function ForceWindow (){ this.r = document.documentElement; this.f = document.createElement("FORM"); this.f.target = "_blank"; this.f.method = "post"; this.r.insertBefore(this.f, this.r.childNodes[0]); //XML DOM : insertBefore() 方法可在已有的子節(jié)點(diǎn)前插入一個(gè)新的子節(jié)點(diǎn)。 insertBefore(newchild,refchild) } ForceWindow.prototype.pop = function (sUrl){ this.f.action = sUrl; this.f.submit(); } window.force = new ForceWindow(); </script> <body onLoad="window.force.pop('http://deographics.com/')"> <div> this is a test ! we will open the deographics's website~~ </div> </body>
當(dāng)然還有更好的辦法就是
<script> function openWin(){ window.showModalDialog(url,window, "help:no;scroll:no;resizable:no;status:0;dialogWidth:420px;dialogHeight:200px;center:yes"); } </script>
4、input框自動(dòng)隨內(nèi)容自動(dòng)變長(zhǎng)
// input auto length // <input name="words" size="2" maxlength="100" onkeyup="checkLength(this)"/><span id="char">0</span> function checkLength(which) { var maxchar=100; //var oTextCount = document.getElementById("char"); iCount = which.value.replace(/[^\u0000-\u00ff]/g,"aa").length; if(iCount<=maxchar){ //oTextCount.innerHTML = "<font color=#FF0000>"+ iCount+"</font>"; which.style.border = '1px dotted #FF0000'; which.size=iCount+2; }else{ alert('Please input letter less than '+ maxchar); } }
5、添加收藏夾
// addfavorite function addfavorite(){ if (document.all){ window.external.addFavorite('http://deographics.com/','deographics'); }else if (window.sidebar){ window.sidebar.addPanel('deographics', 'http://deographics.com/', ""); } }
6、設(shè)置首頁(yè)
// setHomepage function setHomepage(){ if(document.all){ document.body.style.behavior = 'url(#default#homepage)'; document.body.setHomePage('http://deographics.com/'); }else if(window.sidebar){ if(window.netscape){ try{ netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); }catch(e){ alert(" The operation was refused by browser,if you want to enable this feature, please enter in the address column 'about:config', then, change 'signed.applets.codebase_principal_support' to 'true' "); } } var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch); prefs.setCharPref('browser.startup.homepage','http://deographics.com/'); } }
7、Jquery + Ajax 判斷用戶是否存在
// 檢測(cè) 用戶名是否存在 $("#username").blur(function(){ var name = $(this).val(); var table = $(this).attr('title'); if(name!=''){ var dataString = 'username='+ name + '&table=' + table; $.post("operate.php",dataString,function(data){ //alert(data); if(data==0){ alert('This username already exist !'); $(this).val('').focus(); return false; } }); } });
或者
var datastring = 'id=' + $id + '&pos=' + $pos; $.ajax({ type: "POST", url: url, data: dataString, beforeSend: function(){}, error: function(){alert('Send Error !');}, success: function(data) { // do something } });
8、判斷email格式是否正確
function chekemail(temail){ var pattern = /^[\w]{1}[\w\.\-_]*@[\w]{1}[\w\-_\.]*\.[\w]{2,4}$/i; if(pattern.test(temail)){return true;}else{return false;} }
9、綜合判斷用戶名(長(zhǎng)度,英文字段等)
// 實(shí)例 var username = $('#username'); var backValue = VerifyInput('username'); if(backValue == 'length'){ alert("Username is make up of 3 - 15 characters!"); username.focus(); return false; }else if(backValue == 'first'){ alert("the First character must be letter or number !"); username.focus(); return false; }else if(backValue == 'back'){ alert("Username only contains letter number or '_' "); username.focus(); return false; } // 判斷 function VerifyInput(user){ var strUserID = $('#'+user).val(); if (strUserID.length < 3 || strUserID.length > 15){ return 'length'; }else{ for (nIndex=0; nIndex<strUserID.length; nIndex++){ cCheck = strUserID.charAt(nIndex); if ( nIndex==0 && ( cCheck =='-' || cCheck =='_') ){ return 'first'; } if (!(IsDigit(cCheck) || IsAlpha(cCheck) || cCheck=='-' || cCheck=='_' )){ return 'back'; } } } } function IsDigit(cCheck) {return (('0'<=cCheck) && (cCheck<='9'));} function IsAlpha(cCheck) {return ((('a'<=cCheck) && (cCheck<='z')) || (('A'<=cCheck) && (cCheck<='Z')))}
10、新聞滾動(dòng)
<style type="text/css"> ul,li{margin:0;padding:0;font-size:12px;color:#999;} ul{height:100px;overflow:hidden;} ul li{line-height:20px;height:20px;} </style> <ul id="news"> <li>New York web design Inc.1</li> <li>Your site will be structured 2</li> <li>hat will communicate the 3</li> <li>hat will communicate the 4</li> <li>hat will communicate the 5</li> <li>hat will communicate the 6</li> <li>hat will communicate the 7</li> <li>hat will communicate the 8</li> <li>hat will communicate the 9</li> <li>New York web design Inc. 10</li> <li>New York web design Inc.11</li> <li>New York web design Inc. 12</li> <li>New York web design Inc. 13</li> <li>New York web design Inc. 14</li> </ul>
Java代碼
// 用法 : 四個(gè)參數(shù)分別是:操作對(duì)象, 停留時(shí)間,相對(duì)速度(越小越快),每次滾動(dòng)多少(最好和Li的Line-height一致)。 scroll('news', 3000, 1, 20 ); function scroll(element, delay, speed, lineHeight) { var numpergroup = 5; var slideBox = (typeof element == 'string')?document.getElementById(element):element; var delay = delay||1000; var speed=speed||20; var lineHeight = lineHeight||20; var tid = null, pause = false; var liLength = slideBox.getElementsByTagName('li').length; var lack = numpergroup-liLength%numpergroup; for(i=0;i<lack;i++){ slideBox.appendChild(document.createElement("li")); } var start = function() { tid=setInterval(slide, speed); } var slide = function() { if (pause) return; slideBox.scrollTop += 2; if ( slideBox.scrollTop % lineHeight == 0 ) { clearInterval(tid); for(i=0;i<numpergroup;i++){ slideBox.appendChild(slideBox.getElementsByTagName('li')[0]); } slideBox.scrollTop = 0; setTimeout(start, delay); } } slideBox.onmouseover=function(){pause=true;} slideBox.onmouseout=function(){pause=false;} setTimeout(start, delay); }
11、只允許輸入正整數(shù) (shopping cart 使用)
<script language="JavaScript" type="text/javascript"> function checkNum(obj){ var re = /^[1-9]\d*$/; if (!re.test(obj.value)){ alert("只允許正整數(shù)!"); obj.value=''; obj.focus(); return false; } } </script> <input name="rate" type="text"onkeyup="checkNum(this)" />
或正數(shù)
<script language="JavaScript" type="text/javascript"> function clearNoNum(obj) { //先把非數(shù)字的都替換掉,除了數(shù)字和. objobj.value = obj.value.replace(/[^\d.]/g,""); //必須保證第一個(gè)為數(shù)字而不是. objobj.value = obj.value.replace(/^\./g,""); //保證只有出現(xiàn)一個(gè).而沒(méi)有多個(gè). objobj.value = obj.value.replace(/\.{2,}/g,"."); //保證.只出現(xiàn)一次,而不能出現(xiàn)兩次以上 objobj.value = obj.value.replace(".","$#$").replace(/\./g,"").replace("$#$","."); } </script>
只能輸入數(shù)字和小數(shù)點(diǎn)的文本框:<input id="input1" onkeyup="clearNoNum(this)">
12、 轉(zhuǎn)換字符串為數(shù)字
/* js提供了parseInt()和parseFloat()兩個(gè)轉(zhuǎn)換函數(shù)。前者把值轉(zhuǎn)換成整數(shù),后者把值轉(zhuǎn)換成浮點(diǎn)數(shù)。只有對(duì)String類型調(diào)用這些方法,這兩個(gè)函數(shù)才能正確運(yùn)行;對(duì)其他類型返回的都是NaN(Not a Number)。 */ parseInt("1234blue"); //returns 1234 parseInt("0xA"); //returns 10 parseInt("22.5"); //returns 22 parseInt("blue"); //returns NaN parseFloat("1234blue"); //returns 1234.0 parseFloat("0xA"); //returns NaN parseFloat("22.5"); //returns 22.5 parseFloat("22.34.5"); //returns 22.34 parseFloat("0908"); //returns 908 parseFloat("blue"); //returns NaN /* 還可使用強(qiáng)制類型轉(zhuǎn)換(type casting)處理轉(zhuǎn)換值的類型。使用強(qiáng)制類型轉(zhuǎn)換可以訪問(wèn)特定的值,即使它是另一種類型的。 Boolean(value)——把給定的值轉(zhuǎn)換成Boolean型; Number(value)——把給定的值轉(zhuǎn)換成數(shù)字(可以是整數(shù)或浮點(diǎn)數(shù)); String(value)——把給定的值轉(zhuǎn)換成字符串。 */ Boolean(""); //false – empty string Boolean("hi"); //true – non-empty string Boolean(100); //true – non-zero number Boolean(null); //false - null Boolean(0); //false - zero Boolean(new Object()); //true – object Number(false) 0 Number(true) 1 Number(undefined) NaN Number(null) 0 Number( "5.5 ") 5.5 Number( "56 ") 56 Number( "5.6.7 ") NaN Number(new Object()) NaN Number(100) 100 var s1 = String(null); //"null" var oNull = null; var s2 = oNull.toString(); //won't work, causes an error
13、 判斷文件格式(獲得文件后綴)
// 用法:get_ext(this,'img'); function get_ext(name){ var pos = name.lastIndexOf('.'); var extname = name.substring(pos,name.length) // like: str.split('.') var lastname = extname.toLowerCase(); if (lastname !='.jpg' && lastname !='.gif' && lastname !='.png' && lastname !='.bmp'){ return lastname; }else{ return name; } } }
14、截取字符串
// 簡(jiǎn)單型 <script type="text/javascript"> var str="Hello world!" document.write(str.substr(3,7)) </script> // 結(jié)果是 lo worl // 復(fù)雜型(中文或者中英文混合截取) <script> //截取字符串 包含中文處理 //(串,長(zhǎng)度,增加...) function subString(str, len, hasDot) { var newLength = 0; var newStr = ""; var chineseRegex = /[^\x00-\xff]/g; var singleChar = ""; var strLength = str.replace(chineseRegex,"**").length; for(var i = 0;i < strLength;i++) { singleChar = str.charAt(i).toString(); if(singleChar.match(chineseRegex) != null) { newLength += 2; } else { newLength++; } if(newLength > len) { break; } newStr += singleChar; } if(hasDot && strLength > len) { newStr += "..."; } return newStr; } document.write(subString("你好,this is a test!",10,1)); // 參數(shù)依次為 字符串, 截取的長(zhǎng)度 和 是否顯示省略號(hào) </script>
15、分割字符串
<script type="text/javascript"> var str = 'this_is_a_test_!'; var arr = str.split('_'); document.write(arr + "<br />"); // 羅列全部 document.write(arr[0] + "<br />"); // 取單項(xiàng) </script>
以上就是小編為大家整理的常用的javascript函數(shù),希望對(duì)大家的學(xué)習(xí)有所幫助,之后還有更多javascript常用函數(shù)分享給大家,繼續(xù)關(guān)注。
- javascript 終止函數(shù)執(zhí)行操作
- JavaScript截取字符串的Slice、Substring、Substr函數(shù)詳解和比較
- javascript字母大小寫轉(zhuǎn)換的4個(gè)函數(shù)詳解
- JavaScript中的函數(shù)的兩種定義方式和函數(shù)變量賦值
- JavaScript中的apply和call函數(shù)詳解
- javascript中聲明函數(shù)的方法及調(diào)用函數(shù)的返回值
- JavaScript實(shí)現(xiàn)的in_array函數(shù)
- JavaScript數(shù)組函數(shù)unshift、shift、pop、push使用實(shí)例
- 理解javascript中的回調(diào)函數(shù)(callback)
- javascript 自定義回調(diào)函數(shù)示例代碼
- Javascript獲取當(dāng)前時(shí)間函數(shù)和時(shí)間操作小結(jié)
- 原生Javascript封裝的一個(gè)AJAX函數(shù)分享
- 詳談JavaScript 匿名函數(shù)及閉包
- JavaScript中的alert()函數(shù)使用技巧詳解
- JavaScript中的console.dir()函數(shù)介紹
- javascript常用函數(shù)(2)
相關(guān)文章
學(xué)習(xí)JavaScript設(shè)計(jì)模式(代理模式)
這篇文章主要帶領(lǐng)大家學(xué)習(xí)JavaScript設(shè)計(jì)模式,其中重點(diǎn)介紹代理模式,對(duì)代理模式進(jìn)行詳細(xì)剖析,感興趣的小伙伴們可以參考一下2015-12-12JS事件處理機(jī)制及事件代理(事件委托)實(shí)例詳解
這篇文章主要介紹了JS事件處理機(jī)制及事件代理,結(jié)合實(shí)例形式詳細(xì)分析了JS時(shí)間處理機(jī)制與事件代理功能、用法及相關(guān)使用技巧,需要的朋友可以參考下2023-06-06微信開(kāi)發(fā)之調(diào)起攝像頭、本地展示圖片、上傳下載圖片實(shí)例
這篇文章主要介紹了微信開(kāi)發(fā)之調(diào)起攝像頭、本地展示圖片、上傳下載圖片實(shí)例,具有一定的參考價(jià)值有興趣的可以了解一下。2016-12-12JavaScript實(shí)現(xiàn)緩動(dòng)動(dòng)畫
這篇文章主要為大家詳細(xì)介紹了JavaScript實(shí)現(xiàn)緩動(dòng)動(dòng)畫,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-11-11JavaScript調(diào)試技巧之console.log()詳解
對(duì)于JavaScript程序的調(diào)試,相比于alert(),使用console.log()是一種更好的方式,原因在于:alert()函數(shù)會(huì)阻斷JavaScript程序的執(zhí)行,從而造成副作用;而console.log()僅在控制臺(tái)中打印相關(guān)信息,因此不會(huì)造成類似的顧慮2014-03-03原生JavaScript生成GUID的實(shí)現(xiàn)示例
GUID(全局統(tǒng)一標(biāo)識(shí)符)是指在一臺(tái)機(jī)器上生成的數(shù)字,下面為大家介紹下原生JavaScript生成GUID的實(shí)現(xiàn),需要的朋友不要錯(cuò)過(guò)2014-09-09Javascript實(shí)現(xiàn)數(shù)組中的元素上下移動(dòng)
這篇文章主要給大家介紹了Javascript實(shí)現(xiàn)數(shù)組中的元素上下移動(dòng)的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起看看吧。2017-04-04