JavaScript common functions (1) _javascript tips

Source: Internet
Author: User
Tags numeric type casting

Article Main Content list:

1, adjust picture size, not shape (FF IE compatible)/Cut picture (Overflow:hidden)
2, control the number of textarea area text
3, click to display a new window
4, the input box automatically becomes longer with the content automatically
5, add Favorite Folders
6, set the home page
7, Jquery + Ajax to determine whether the user exists
8, to determine whether the e-mail format is correct
9, the Comprehensive Judgment user name (length, English text paragraph and so on)
10, news Rolling
11. Allow only positive integers (shopping cart) or positive numbers (positive integers and positive decimals)
12. Convert strings to Numbers
13. Determine file format (get file suffix)
14, intercept the string
15. Split string

Main content:
1, adjust the picture size, not shape (FF IE compatible)

Usage  
 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 
  }} 
  } 
  
 

To cut through Overflow:hidden:

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 
  }}  
 } 
 

Instance:

<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;o Ver-flow:hidden;} 
</style> 
<ul> 
 <li></li > 
 <li></li> 
</ul> 

2, control the number of textarea area text

<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 = $ (textar 
 
 EA). 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.valu 
 
 E.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= "onkeyup=" Charsremain (this, MB, ' textarea '); " 
 ></textarea> <span id= "Textarea_charsremain" >250</span> characters remaining

3, click to display a new window

Play window 
function G_openwindow (Pageurl, Innerwidth, innerheight) 
{ 
 var screenwidth = screen.availwidth 
 var screenheight = Screen.availheight 
 var startx = (screenwidth-innerwidth)/2 
 var starty = (Screenheight-inn Erheight)/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 code:

<script language= "JavaScript" > 
 //Automatic pop-up window 
 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> 

Unfortunately, many browsers will block pop-up windows, you need to manually allow the rear to see! The following is a forced pop-up window, which is the principle of creating a form that is opened by post.

<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]); The XML Dom:insertbefore () method inserts a new child node before an existing child node. 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'll open the Deographics ' s website~~ 
 </div> 
</body> 

And, of course, there's a better way.

<script> 
 function Openwin () { 
 window.showmodaldialog (Url,window, "help:no;scroll:no;resizable:no; Status:0;dialogwidth:420px;dialogheight:200px;center:yes "); 
 } 

4, the input box automatically becomes longer with the content automatically

Input Auto Length 
 //<input name= "Words" size= "2" maxlength= "M" 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, add Favorite Folders

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, set the home page

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 is refused by browser,if your want to enable this feature, please enter in the Addres S 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 to determine whether the user exists

Detects if the user name exists 
$ ("#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;} 
  } 
 ); 
}); 

Or

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, to determine whether the e-mail format is correct

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, the Comprehensive Judgment user name (length, English text paragraph and so on)

instance 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 = = ' I ') {alert ("the" the "the" "The" "The" "the" the "the" the ""); 
  Username.focus (); 
 return false; 
  }else if (Backvalue = = ' back ') {alert ("Username only contains letter number or ' _ '"); 
  Username.focus (); 
 return false; 
 }//Judge function Verifyinput (user) {var strUserID = $ (' # ' +user). Val (); 
 if (Struserid.length < 3 | | | struserid.length >) {return ' length '; 
  }else{for (nindex=0 nindex<struserid.length; nindex++) {Ccheck = Struserid.charat (nindex); 
    if (nindex==0 && = (Ccheck = = ' | | | ccheck = = ' _ ')) {return ' a '; } if (! ( IsDigit (Ccheck) | | Isalpha (Ccheck) | | ccheck== '-' | | 
    ccheck== ' _ ') {return ' back '; }}} function IsDigit (Ccheck) {return (' 0 ' <=ccheck) &&amP 
 (ccheck<= ' 9 '));} function Isalpha (Ccheck) {return ((' a ' <=ccheck) && (ccheck<= ' z ')) | | 
 ((' A ' <=ccheck) && (ccheck<= ' Z '))}

10, News scrolling

 <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 would be Stru 
 Ctured 2</li> <li>hat would communicate the 3</li> <li>hat'll communicate the 4</li> <li>hat would communicate the 5</li> <li>hat would communicate the 6</li> <li>hat would c Ommunicate the 7</li> <li>hat would communicate the 8</li> <li>hat would communicate the 9</L I> <li>new York web Design Inc. 10</li> <li>new York web Design inc.11</li> <li>n EW York web Design inc. 12</li> <li>new York web Design Inc. 13</li> <li>new York web Design I nc. 14</li> </ul> 

Java code  

Usage: Four parameters are: Operation object, residence time, relative speed (the smaller the faster), each scrolling how much (preferably with Li's line-height consistent). 
 
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")); 
 The 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, only allow input positive integer (shopping cart use)

<script language= "JavaScript" type= "text/javascript" > 
function checknum (obj) { 
 var re =/^[1-9]\d*$/; 
 if (!re.test (Obj.value)) { 
 alert ("Allow only positive integers!"); 
 Obj.value= '; 
 Obj.focus (); 
 return false; 
 } 
} 
</script> 
 

or positive number

<script language= "JavaScript" type= "text/javascript" > 
 function clearnonum (obj) 
 { 
 // First, replace the non-numeric, except for the numbers and. 
 Objobj.value = Obj.value.replace (/[^\d.) /g, ""); 
 The first one must be guaranteed to be number instead of. 
 Objobj.value = Obj.value.replace (/^\./g, ""); 
 Ensure that only one is present. and not multiple. 
 Objobj.value = Obj.value.replace (/\.{ 2,}/g, "."); 
 Guaranteed. Occurs only once, and cannot appear more than two times 
 objobj.value = Obj.value.replace (".", "$#$"). Replace (/\./g, ""). Replace ("$#$", ".") 
 ; 
</script> 

Text boxes that can only enter numbers and decimal places: <input id= "input1" onkeyup= "Clearnonum (This)" >&NBSP;&NBSP;
12, convert string to numeric

/* JS provides parseint () and parsefloat () two conversion functions. The former converts the value to an integer, and the latter converts the value to a floating-point number. 
These methods are invoked only on the string type, and the two functions are run correctly, and all other types are returned as Nan (not a number). * * parseint ("1234blue"); Returns 1234 parseint ("0xA"); Returns parseint ("22.5"); Returns 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/* also uses coercion type conversion (type casting) to handle the type of the converted value. 
You can use coercion type conversions to access a specific value, even if it is of another type. 
Boolean (value)-Converts a given value to a Boolean, number (value)-Converts a given value to numbers (which can be integers or floating-point numbers); string (value)--converts a given value to a string. * * 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 ("5 6 ") NumbeR ("5.6.7") Nan Number (new Object ()) Nan number (a) var S1 = String (null); 
"NULL" var onull = null; var s2 = onull.tostring (); Won ' t work, causes an error

13. Determine file format (get file suffix)

Usage: 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, intercept the string

Simple Type 
 
<script type= "Text/javascript" > 
 
var str= "Hello world!" 
document.write (Str.substr (3,7)) 
 
</script> 
 
//result is lo worl 
 
 
//complex (Chinese or English mixed interception) 
 
<script> 
//Intercept string contains Chinese processing 
//(string, length, increase ...) 
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 ("Hello, this is a test!", 10, 1)); The arguments are string, the length of the intercept, and whether the ellipsis is displayed 

15. Split string

<script type= "Text/javascript" > 
 
var str = ' this_is_a_test_! '; 
var arr = Str.split ('_'); 
 
document.write (arr + "<br/>"); List all 
document.write (arr[0] + "<br/>");//Take single 
 
</script>

The above is a small series for everyone to tidy up the commonly used JavaScript functions, I hope to learn some help, and then there are more common functions of JavaScript to share to everyone, continue to pay attention to.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.