麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

首頁 > 語言 > JavaScript > 正文

javascript常用函數(上)

2024-05-06 16:24:56
字體:
來源:轉載
供稿:網友

這篇文章主要介紹了javascript常用函數,15個常用函數,都具有很高的實用性,感興趣的小伙伴們可以參考一下

文章主要內容列表:

1、 調整圖片大小,不走形(FF IE 兼容)/ 剪切圖片(overflow:hidden)

2、 控制textarea區域文字數量

3、 點擊顯示新窗口

4、 input框自動隨內容自動變長

5、 添加收藏夾

6、 設置首頁

7、 Jquery + Ajax 判斷用戶是否存在

8、 判斷email格式是否正確

9、 綜合判斷用戶名(長度,英文字段等)

10、新聞滾動

11、 只允許輸入正整數 (shopping cart 使用) 或者 正數 (正整數和正小數)

12、 轉換字符串為數字

13、 判斷文件格式(獲得文件后綴)

14、 截取字符串

15、分割字符串

主要內容:

1、 調整圖片大小,不走形(FF IE 兼容)

 

  1. // 用法 <img src="this_image_path.jpg" onload="DrawImage(this,450,450);" />  
  2. function DrawImage(ImgD,FitWidth,FitHeight){  
  3. var image=new Image();  
  4. image.src=ImgD.src;  
  5. if(image.width>0 && image.height>0){  
  6. if(image.width/image.height>= FitWidth/FitHeight){  
  7. if(image.width>FitWidth){  
  8. ImgD.width=FitWidth;  
  9. ImgD.height=(image.height*FitWidth)/image.width;  
  10. }else{  
  11. ImgD.width=image.width;  
  12. ImgD.height=image.height;  
  13. }  
  14. else{  
  15. if(image.height>FitHeight){  
  16. ImgD.height=FitHeight;  
  17. ImgD.width=(image.width*FitHeight)/image.height;  
  18. }else{  
  19. ImgD.width=image.width;  
  20. ImgD.height=image.height;  
  21. }  
  22. }  
  23. }  

通過 overflow:hidden進行剪切:

 

 
  1. function clipImage(o, w, h){  
  2. var img = new Image();  
  3. img.src = o.src;  
  4. if(img.width >0 && img.height>0)  
  5. {  
  6. if(img.width/img.height >= w/h)  
  7. {  
  8. if(img.width > w)  
  9. {  
  10. o.width = (img.width*h)/img.height;  
  11. o.height = h;  
  12. //o.setAttribute("style", "marginLeft:-" + ((o.width-w)/2).toString() + "px");  
  13. $(o).css("margin-left""-"+((o.width-w)/2).toString() + "px");  
  14. }  
  15. else 
  16. {  
  17. o.width = img.width;  
  18. o.height = img.height;  
  19. }  
  20. }  
  21. else 
  22. {  
  23. if(img.height > h)  
  24. {  
  25. o.height = (img.height*w)/img.width;  
  26. o.width = w;  
  27. //o.setAttribute("style", "margin-top:-" + ((o.height-h)/2).toString() + "px");  
  28. //$(o).css("style", "margin-top:-" + ((o.height-h)/2).toString() + "px");  
  29. $(o).css("margin-top""-"+((o.height-h)/2).toString() + "px");  
  30. }  
  31. else 
  32. {  
  33. o.width = img.width;  
  34. o.height = img.height;  
  35. }  
  36. }  
  37. }  
  38. }  

實例:

 

 
  1. <style type="text/css">  
  2. ul{list-style:none;}  
  3. ul li{float:left;padding:1px;border:#ccc 1px solid;width:120px;height:120px;overflow:hidden;text-align:center;over-flow:hidden;}  
  4. </style>  
  5. <ul>  
  6. <li><img src="1.jpg" onload="DrawImage(this,120,120);" /></li>  
  7. <li><img src="2.jpg" onload="clipImage(this,120,120);" /></li>  
  8. </ul>  

2、控制textarea區域文字數量

 

 
  1. <script>  
  2. /**  
  3. * Calculate how many characters remain in a textarea (jQuery)  
  4. * @param string textarea  
  5. * @param int maxLength  
  6. * @param string div  
  7. */ 
  8. function charsRemain(textarea, maxLength, div) {  
  9. var currentLength = $(textarea).val().length;  
  10.  
  11. var charsLeft = maxLength - currentLength;  
  12. if (charsLeft < 0) { charsLeft = 0; }  
  13.  
  14. $("#"+ div +"_charsRemain").html(charsLeft);  
  15.  
  16. if (currentLength > maxLength) {  
  17. var fullText = $(textarea).val().substring(0, maxLength);  
  18. $(textarea).val(fullText);  
  19. }  
  20. }  
  21.  
  22. /**  
  23. * Calculate how many characters remain in a textarea (javascript)  
  24. * @param string textarea  
  25. * @param int maxLength  
  26. * @param string div  
  27. */ 
  28. function charsRemain(textarea, maxLength, div) {  
  29. var currentLength = textarea.value.length;  
  30.  
  31. var charsLeft = maxLength - currentLength;  
  32. if (charsLeft < 0) { charsLeft = 0; }  
  33.  
  34. document.getElementById(div +"_charsRemain").innerHTML = charsLeft;  
  35.  
  36. if (currentLength > maxLength) {  
  37. var fullText = textarea.value.substring(0, maxLength);  
  38. textarea.value = fullText;  
  39. }  
  40. }  
  41. </script>  
  42.  
  43. <textarea rows="5" cols="15" onkeyup="charsRemain(this, 250, 'textarea');"></textarea>  
  44.  
  45. <span id="textarea_charsRemain">250</span> characters remaining  

3、點擊顯示新窗口

 

 
  1. //彈窗  
  2. function g_OpenWindow(pageURL, innerWidth, innerHeight)  
  3. {  
  4. var ScreenWidth = screen.availWidth  
  5. var ScreenHeight = screen.availHeight  
  6. var StartX = (ScreenWidth - innerWidth) / 2  
  7. var StartY = (ScreenHeight - innerHeight) / 2  
  8. 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')  
  9. wins.focus();  
  10. }  

Java代碼:

 

 
  1. <script language="JavaScript">  
  2. // 自動彈出窗口  
  3. 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');  
  4. whatsNew.document.write('<center><b>news</b>< /center>');  
  5. whatsNew.document.write('<p>this is a test');  
  6. whatsNew.document.write('<p>deos address');  
  7. whatsNew.document.write('<p align="right">' + '<a href="javascript:self.close()">Close</a>');  
  8. whatsNew.document.close();  
  9. </script>  

不幸的是,很多瀏覽器會屏蔽彈出窗口,你需要手動允許后方可看到!下面是強制彈出窗口,原理就是創建一個form,通過post打開。

 

 
  1. <script language="javascript">  
  2. function ForceWindow (){  
  3. this.r = document.documentElement;  
  4. this.f = document.createElement("FORM");  
  5. this.f.target = "_blank";  
  6. this.f.method = "post";  
  7. this.r.insertBefore(this.f, this.r.childNodes[0]); //XML DOM : insertBefore() 方法可在已有的子節點前插入一個新的子節點。 insertBefore(newchild,refchild)  
  8. }  
  9.  
  10. ForceWindow.prototype.pop = function (sUrl){  
  11. this.f.action = sUrl;  
  12. this.f.submit();  
  13. }  
  14.  
  15. window.force = new ForceWindow();  
  16. </script>  
  17.  
  18. <body onLoad="window.force.pop('http://deographics.com/')">  
  19. <div>  
  20. this is a test ! we will open the deographics's website~~  
  21. </div>  
  22. </body>  

當然還有更好的辦法就是

 

 
  1. <script>  
  2. function openWin(){  
  3. window.showModalDialog(url,window, "help:no;scroll:no;resizable:no;status:0;dialogWidth:420px;dialogHeight:200px;center:yes");  
  4. }  
  5. </script> 

4、input框自動隨內容自動變長

 

 
  1. // input auto length  
  2. // <input name="words" size="2" maxlength="100" onkeyup="checkLength(this)"/><span id="char">0</span>  
  3.  
  4. function checkLength(which) {  
  5. var maxchar=100;  
  6. //var oTextCount = document.getElementById("char");  
  7. iCount = which.value.replace(/[^/u0000-/u00ff]/g,"aa").length;  
  8. if(iCount<=maxchar){  
  9. //oTextCount.innerHTML = "<font color=#FF0000>"+ iCount+"</font>";  
  10. which.style.border = '1px dotted #FF0000';  
  11. which.size=iCount+2;  
  12. }else{  
  13. alert('Please input letter less than '+ maxchar);  
  14. }  
  15. }  

5、添加收藏夾

 

 
  1. // addfavorite  
  2. function addfavorite(){  
  3. if (document.all){  
  4. window.external.addFavorite('http://deographics.com/','deographics');  
  5. }else if (window.sidebar){  
  6. window.sidebar.addPanel('deographics''http://deographics.com/'"");  
  7. }  
  8. }  

6、設置首頁

 

 
  1. // setHomepage  
  2. function setHomepage(){  
  3. if(document.all){  
  4. document.body.style.behavior = 'url(#default#homepage)';  
  5. document.body.setHomePage('http://deographics.com/');  
  6. }else if(window.sidebar){  
  7. if(window.netscape){  
  8. try{  
  9. netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");  
  10. }catch(e){  
  11. 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' ");  
  12. }  
  13. }  
  14. var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);  
  15. prefs.setCharPref('browser.startup.homepage','http://deographics.com/');  
  16. }  

7、Jquery + Ajax 判斷用戶是否存在

 

 
  1. // 檢測 用戶名是否存在  
  2. $("#username").blur(function(){  
  3. var name = $(this).val(); var table = $(this).attr('title');  
  4. if(name!=''){  
  5. var dataString = 'username='+ name + '&table=' + table;  
  6. $.post("operate.php",dataString,function(data){ //alert(data);  
  7. if(data==0){  
  8. alert('This username already exist !'); $(this).val('').focus(); return false;  
  9. }  
  10. });  
  11. }  
  12. });  

或者

 

 
  1. var datastring = 'id=' + $id + '&pos=' + $pos;  
  2. $.ajax({  
  3. type: "POST",  
  4. url: url,  
  5. data: dataString,  
  6. beforeSend: function(){},  
  7. error: function(){alert('Send Error !');},  
  8. success: function(data) {  
  9. // do something  
  10. }  
  11. });  

8、判斷email格式是否正確

 

 
  1. function chekemail(temail){  
  2. var pattern = /^[/w]{1}[/w/./-_]*@[/w]{1}[/w/-_/.]*/.[/w]{2,4}$/i;  
  3. if(pattern.test(temail)){return true;}else{return false;}  

9、綜合判斷用戶名(長度,英文字段等)

 

 
  1. // 實例  
  2. var username = $('#username');  
  3. var backValue = VerifyInput('username');  
  4.  
  5. if(backValue == 'length'){  
  6. alert("Username is make up of 3 - 15 characters!");  
  7. username.focus();  
  8. return false;  
  9. }else if(backValue == 'first'){  
  10. alert("the First character must be letter or number !");  
  11. username.focus();  
  12. return false;  
  13. }else if(backValue == 'back'){  
  14. alert("Username only contains letter number or '_' ");  
  15. username.focus();  
  16. return false;  
  17. }  
  18. // 判斷  
  19. function VerifyInput(user){  
  20. var strUserID = $('#'+user).val();  
  21. if (strUserID.length < 3 || strUserID.length > 15){  
  22. return 'length';  
  23. }else{  
  24. for (nIndex=0; nIndex<strUserID.length; nIndex++){  
  25. cCheck = strUserID.charAt(nIndex);  
  26. if ( nIndex==0 && ( cCheck =='-' || cCheck =='_') ){  
  27. return 'first';  
  28. }  
  29. if (!(IsDigit(cCheck) || IsAlpha(cCheck) || cCheck=='-' || cCheck=='_' )){  
  30. return 'back';  
  31. }  
  32. }  
  33. }  
  34. }  
  35. function IsDigit(cCheck) {return (('0'<=cCheck) && (cCheck<='9'));}  
  36. function IsAlpha(cCheck) {return ((('a'<=cCheck) && (cCheck<='z')) || (('A'<=cCheck) && (cCheck<='Z')))}  

10、新聞滾動

 

 
  1. <style type="text/css">  
  2. ul,li{margin:0;padding:0;font-size:12px;color:#999;}  
  3. ul{height:100px;overflow:hidden;}  
  4. ul li{line-height:20px;height:20px;}  
  5. </style>  
  6.  
  7. <ul id="news">  
  8. <li>New York web design Inc.1</li>  
  9. <li>Your site will be structured 2</li>  
  10. <li>hat will communicate the 3</li>  
  11.  
  12. <li>hat will communicate the 4</li>  
  13. <li>hat will communicate the 5</li>  
  14. <li>hat will communicate the 6</li>  
  15. <li>hat will communicate the 7</li>  
  16. <li>hat will communicate the 8</li>  
  17. <li>hat will communicate the 9</li>  
  18.  
  19. <li>New York web design Inc. 10</li>  
  20. <li>New York web design Inc.11</li>  
  21. <li>New York web design Inc. 12</li>  
  22. <li>New York web design Inc. 13</li>  
  23. <li>New York web design Inc. 14</li>  
  24. </ul> 

Java代碼

 

 
  1. // 用法 : 四個參數分別是:操作對象, 停留時間,相對速度(越小越快),每次滾動多少(最好和Li的Line-height一致)。  
  2.  
  3. scroll('news', 3000, 1, 20 );  
  4.  
  5. function scroll(element, delay, speed, lineHeight) {  
  6. var numpergroup = 5;  
  7. var slideBox = (typeof element == 'string')?document.getElementById(element):element;  
  8. var delay = delay||1000;  
  9. var speed=speed||20;  
  10. var lineHeight = lineHeight||20;  
  11. var tid = null, pause = false;  
  12. var liLength = slideBox.getElementsByTagName('li').length;  
  13. var lack = numpergroup-liLength%numpergroup;  
  14. for(i=0;i<lack;i++){  
  15. slideBox.appendChild(document.createElement("li"));  
  16. }  
  17. var start = function() {  
  18. tid=setInterval(slide, speed);  
  19. }  
  20. var slide = function() {  
  21. if (pause) return;  
  22. slideBox.scrollTop += 2;  
  23. if ( slideBox.scrollTop % lineHeight == 0 ) {  
  24. clearInterval(tid);  
  25. for(i=0;i<numpergroup;i++){  
  26. slideBox.appendChild(slideBox.getElementsByTagName('li')[0]);  
  27. }  
  28. slideBox.scrollTop = 0;  
  29. setTimeout(start, delay);  
  30. }  
  31. }  
  32. slideBox.onmouseover=function(){pause=true;}  
  33. slideBox.onmouseout=function(){pause=false;}  
  34. setTimeout(start, delay);  
  35. }  

11、只允許輸入正整數 (shopping cart 使用)

 

 
  1. <script language="JavaScript" type="text/javascript">  
  2. function checkNum(obj){  
  3. var re = /^[1-9]/d*$/;  
  4. if (!re.test(obj.value)){  
  5. alert("只允許正整數!");  
  6. obj.value='';  
  7. obj.focus();  
  8. return false;  
  9. }  
  10. }  
  11. </script>  
  12.  
  13. <input name="rate" type="text"onkeyup="checkNum(this)" /> 

或正數

 

 
  1. <script language="JavaScript" type="text/javascript">  
  2. function clearNoNum(obj)  
  3. {  
  4. //先把非數字的都替換掉,除了數字和.  
  5. objobj.value = obj.value.replace(/[^/d.]/g,"");  
  6. //必須保證第一個為數字而不是.  
  7. objobj.value = obj.value.replace(/^/./g,"");  
  8. //保證只有出現一個.而沒有多個.  
  9. objobj.value = obj.value.replace(//.{2,}/g,".");  
  10. //保證.只出現一次,而不能出現兩次以上  
  11. objobj.value = obj.value.replace(".","$#$").replace(//./g,"").replace("$#$",".");  
  12. }  
  13. </script>  

只能輸入數字和小數點的文本框:<input id="input1" onkeyup="clearNoNum(this)">  

12、 轉換字符串為數字

 

 
  1. /*  
  2. js提供了parseInt()和parseFloat()兩個轉換函數。前者把值轉換成整數,后者把值轉換成浮點數。只有對String類型調用這些方法,這兩個函數才能正確運行;對其他類型返回的都是NaN(Not a Number)。  
  3. */ 
  4.  
  5. parseInt("1234blue"); //returns 1234  
  6. parseInt("0xA"); //returns 10  
  7. parseInt("22.5"); //returns 22  
  8. parseInt("blue"); //returns NaN  
  9.  
  10. parseFloat("1234blue"); //returns 1234.0  
  11. parseFloat("0xA"); //returns NaN  
  12. parseFloat("22.5"); //returns 22.5  
  13. parseFloat("22.34.5"); //returns 22.34  
  14. parseFloat("0908"); //returns 908  
  15. parseFloat("blue"); //returns NaN  
  16.  
  17. /*  
  18. 還可使用強制類型轉換(type casting)處理轉換值的類型。使用強制類型轉換可以訪問特定的值,即使它是另一種類型的。  
  19. Boolean(value)——把給定的值轉換成Boolean型;  
  20. Number(value)——把給定的值轉換成數字(可以是整數或浮點數);  
  21. String(value)——把給定的值轉換成字符串。  
  22. */ 
  23.  
  24. Boolean(""); //false – empty string  
  25. Boolean("hi"); //true – non-empty string  
  26. Boolean(100); //true – non-zero number  
  27. Boolean(null); //false - null  
  28. Boolean(0); //false - zero  
  29. Boolean(new Object()); //true – object  
  30.  
  31. Number(false) 0  
  32. Number(true) 1  
  33. Number(undefined) NaN  
  34. Number(null) 0  
  35. Number( "5.5 ") 5.5  
  36. Number( "56 ") 56  
  37. Number( "5.6.7 ") NaN  
  38. Number(new Object()) NaN  
  39. Number(100) 100  
  40.  
  41. var s1 = String(null); //"null"  
  42. var oNull = null;  
  43. var s2 = oNull.toString(); //won't work, causes an error 

13、 判斷文件格式(獲得文件后綴)

 

 
  1. // 用法:get_ext(this,'img');  
  2.  
  3. function get_ext(name){  
  4. var pos = name.lastIndexOf('.');  
  5. var extname = name.substring(pos,name.length) // like: str.split('.')  
  6. var lastname = extname.toLowerCase();  
  7.  
  8. if (lastname !='.jpg' && lastname !='.gif' && lastname !='.png' && lastname !='.bmp'){  
  9. return lastname;  
  10. }else{  
  11. return name;  
  12. }  
  13. }  
  14. }  

14、截取字符串

 

 
  1. // 簡單型  
  2.  
  3. <script type="text/javascript">  
  4.  
  5. var str="Hello world!" 
  6. document.write(str.substr(3,7))  
  7.  
  8. </script>  
  9.  
  10. // 結果是 lo worl  
  11.  
  12.  
  13. // 復雜型(中文或者中英文混合截取)  
  14.  
  15. <script>  
  16. //截取字符串 包含中文處理  
  17. //(串,長度,增加...)  
  18. function subString(str, len, hasDot)  
  19. {  
  20. var newLength = 0;  
  21. var newStr = "";  
  22. var chineseRegex = /[^/x00-/xff]/g;  
  23. var singleChar = "";  
  24. var strLength = str.replace(chineseRegex,"**").length;  
  25. for(var i = 0;i < strLength;i++)  
  26. {  
  27. singleChar = str.charAt(i).toString();  
  28. if(singleChar.match(chineseRegex) != null)  
  29. {  
  30. newLength += 2;  
  31. }  
  32. else 
  33. {  
  34. newLength++;  
  35. }  
  36. if(newLength > len)  
  37. {  
  38. break;  
  39. }  
  40. newStr += singleChar;  
  41. }  
  42.  
  43. if(hasDot && strLength > len)  
  44. {  
  45. newStr += "...";  
  46. }  
  47. return newStr;  
  48. }  
  49.  
  50. document.write(subString("你好,this is a test!",10,1)); // 參數依次為 字符串, 截取的長度 和 是否顯示省略號  
  51. </script> 

15、分割字符串

 

 
  1. <script type="text/javascript">  
  2.  
  3. var str = 'this_is_a_test_!';  
  4. var arr = str.split('_');  
  5.  
  6. document.write(arr + "<br />"); // 羅列全部  
  7. document.write(arr[0] + "<br />"); // 取單項  
  8.  
  9. </script> 

以上就是小編為大家整理的常用的javascript函數,希望對大家的學習有所幫助,之后還有更多javascript常用函數分享給大家,繼續關注。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 手机视频在线播放 | 欧洲精品久久久 | 国产二区三区四区 | 国产91丝袜在线播放 | 国产永久免费观看 | 国产一区免费视频 | 在线a亚洲视频播放在线观看 | 一区二区免费看 | 精品在线一区二区三区 | 亚洲热线99精品视频 | 国产一区精品视频 | 毛片电影在线看 | 午夜精品毛片 | 免费男女视频 | 久久久av亚洲男天堂 | 国产一级一片免费播放 | 午夜视频你懂的 | h视频免费观看 | 毛片a级毛片免费播放100 | 久久亚洲激情 | 国产一国产一级毛片视频在线 | 欧美日本在线视频 | 91精品成人福利在线播放 | 亚洲小视频网站 | 欧美日韩在线播放 | 欧美性激情视频 | 欧美精品一区二区三区在线 | 最新se94se在线欧美 | 视频一区免费观看 | 久久久久久中文字幕 | 日本a大片 | 久久亚洲成人网 | 日本高清一级片 | 亚洲小视频在线观看,com | 亚洲极色 | 高清国产午夜精品久久久久久 | 亚洲草逼视频 | 黄色大片在线免费观看 | 精品无吗乱吗av国产爱色 | 一级毛片看 | 国产寡妇xxxxxxxx性开放 |