首页 > 语言 > 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常用函数分享给大家,继续关注。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选