Home Web Front-end JS Tutorial Commonly used functions in javascript (1)_javascript skills

Commonly used functions in javascript (1)_javascript skills

May 16, 2016 pm 03:33 PM

List of main contents of the article:

1. Adjust the image size without losing shape (FF IE compatible)/cut the image (overflow:hidden)
2. Control the number of texts in the textarea
3. Click to display a new window
4. The input box automatically grows longer with the content
5. Add favorites
6. Set up home page
7. Jquery Ajax determines whether the user exists
8. Determine whether the email format is correct
9. Comprehensive judgment of username (length, English field, etc.)
10. News scroll
11. Only positive integers (used by shopping cart) or positive numbers (positive integers and positive decimals) are allowed
12. Convert string to number
13. Determine the file format (get the file suffix)
14. Intercept string
15. Split string

Main content:
1. Adjust the image size without losing shape (FF IE compatible)

// 用法 <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; 
  } 
  } 
 } 
 } 
Copy after login

Cut via 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; 
  }  
 } 
 } 
} 
Copy after login

Example:

<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> 
Copy after login

2. Control the amount of text in the textarea

<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 
Copy after login

3. Click to display the new window

//弹窗 
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(); 
} 
Copy after login

Java code:

<script language="JavaScript"> 
 // 自动弹出窗口 
 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> 
Copy after login

Unfortunately, many browsers block pop-up windows, and you need to manually allow them before you can see them! The following is a forced pop-up window. The principle is to create a form and open it through 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]); //XML DOM : insertBefore() 方法可在已有的子节点前插入一个新的子节点。 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> 
Copy after login

Of course there is a better way

<script> 
 function openWin(){ 
 window.showModalDialog(url,window, "help:no;scroll:no;resizable:no;status:0;dialogWidth:420px;dialogHeight:200px;center:yes"); 
 } 
</script> 
Copy after login

4. The input box automatically grows longer with the content

// 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); 
 } 
 } 
Copy after login

5. Add favorites

// addfavorite 
 function addfavorite(){ 
 if (document.all){ 
  window.external.addFavorite('http://deographics.com/','deographics'); 
 }else if (window.sidebar){ 
  window.sidebar.addPanel('deographics', 'http://deographics.com/', ""); 
 } 
 } 
Copy after login

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 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/'); 
 } 
 }
Copy after login

7. Jquery Ajax determines whether the user 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; 
  } 
 }); 
 } 
}); 
Copy after login

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 
 } 
 }); 
Copy after login

8. Determine whether the email 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;} 
} 
Copy after login

9. Comprehensive judgment of username (length, English field, etc.)

// 实例 
 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')))} 
Copy after login

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 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> 
Copy after login

Java code

// 用法 : 四个参数分别是:操作对象, 停留时间,相对速度(越小越快),每次滚动多少(最好和Li的Line-height一致)。 
 
scroll('news', 3000, 1, 20 ); 
 
function scroll(element, delay, speed, lineHeight) { 
 var numpergroup = 5; 
 var slideBox = (typeof element == 'string')&#63;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); 
} 
Copy after login

11. Only positive integers are allowed (for shopping cart use)

<script language="JavaScript" type="text/javascript"> 
function checkNum(obj){ 
 var re = /^[1-9]\d*$/; 
 if (!re.test(obj.value)){ 
 alert("只允许正整数!"); 
 obj.value=''; 
 obj.focus(); 
 return false; 
 } 
} 
</script> 
 
<input name="rate" type="text"onkeyup="checkNum(this)" /> 
Copy after login

or positive number

<script language="JavaScript" type="text/javascript"> 
 function clearNoNum(obj) 
 { 
 //先把非数字的都替换掉,除了数字和. 
 objobj.value = obj.value.replace(/[^\d.]/g,""); 
 //必须保证第一个为数字而不是. 
 objobj.value = obj.value.replace(/^\./g,""); 
 //保证只有出现一个.而没有多个. 
 objobj.value = obj.value.replace(/\.{2,}/g,"."); 
 //保证.只出现一次,而不能出现两次以上 
 objobj.value = obj.value.replace(".","$#$").replace(/\./g,"").replace("$#$","."); 
 } 
</script> 
Copy after login

A text box that can only enter numbers and decimal points:
12. Convert string to number

/* 
js提供了parseInt()和parseFloat()两个转换函数。前者把值转换成整数,后者把值转换成浮点数。只有对String类型调用这些方法,这两个函数才能正确运行;对其他类型返回的都是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 
 
/* 
还可使用强制类型转换(type casting)处理转换值的类型。使用强制类型转换可以访问特定的值,即使它是另一种类型的。 
Boolean(value)——把给定的值转换成Boolean型; 
Number(value)——把给定的值转换成数字(可以是整数或浮点数); 
String(value)——把给定的值转换成字符串。 
*/ 
 
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
Copy after login

13. Determine the file format (get the file suffix)

// 用法: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; 
 } 
 } 
} 
Copy after login

14. Intercept string

// 简单型 
 
<script type="text/javascript"> 
 
var str="Hello world!" 
document.write(str.substr(3,7)) 
 
</script> 
 
// 结果是 lo worl 
 
 
// 复杂型(中文或者中英文混合截取) 
 
<script> 
//截取字符串 包含中文处理 
//(串,长度,增加...) 
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)); // 参数依次为 字符串, 截取的长度 和 是否显示省略号 
</script> 
Copy after login

15. Split string

<script type="text/javascript"> 
 
var str = 'this_is_a_test_!'; 
var arr = str.split('_'); 
 
document.write(arr + "<br />"); // 罗列全部 
document.write(arr[0] + "<br />"); // 取单项 
 
</script>
Copy after login

The above are the commonly used javascript functions compiled by the editor for everyone. I hope it will be helpful to everyone's learning. There will be more common javascript functions to share with you in the future, so continue to pay attention.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Replace String Characters in JavaScript Replace String Characters in JavaScript Mar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

8 Stunning jQuery Page Layout Plugins 8 Stunning jQuery Page Layout Plugins Mar 06, 2025 am 12:48 AM

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

Build Your Own AJAX Web Applications Build Your Own AJAX Web Applications Mar 09, 2025 am 12:11 AM

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

10 jQuery Fun and Games Plugins 10 jQuery Fun and Games Plugins Mar 08, 2025 am 12:42 AM

10 fun jQuery game plugins to make your website more attractive and enhance user stickiness! While Flash is still the best software for developing casual web games, jQuery can also create surprising effects, and while not comparable to pure action Flash games, in some cases you can also have unexpected fun in your browser. jQuery tic toe game The "Hello world" of game programming now has a jQuery version. Source code jQuery Crazy Word Composition Game This is a fill-in-the-blank game, and it can produce some weird results due to not knowing the context of the word. Source code jQuery mine sweeping game

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

Load Box Content Dynamically using AJAX Load Box Content Dynamically using AJAX Mar 06, 2025 am 01:07 AM

This tutorial demonstrates creating dynamic page boxes loaded via AJAX, enabling instant refresh without full page reloads. It leverages jQuery and JavaScript. Think of it as a custom Facebook-style content box loader. Key Concepts: AJAX and jQuery

jQuery Parallax Tutorial - Animated Header Background jQuery Parallax Tutorial - Animated Header Background Mar 08, 2025 am 12:39 AM

This tutorial demonstrates how to create a captivating parallax background effect using jQuery. We'll build a header banner with layered images that create a stunning visual depth. The updated plugin works with jQuery 1.6.4 and later. Download the

How to Write a Cookie-less Session Library for JavaScript How to Write a Cookie-less Session Library for JavaScript Mar 06, 2025 am 01:18 AM

This JavaScript library leverages the window.name property to manage session data without relying on cookies. It offers a robust solution for storing and retrieving session variables across browsers. The library provides three core methods: Session

See all articles