JavaScript RND - innerHTML的简单模板

function RND(tmpl, ns) {
  var fn = function(w, g) {
    g = g.split("|");
    var cnt = ns[g[0]];
    for(var i=1; i < g.length; i++)
      cnt = eval(g[i])(cnt);
    return cnt || w;
  };
  return tmpl.replace(/%(([A-Za-z0-9_|.]*))/g, fn);
}

JavaScript 序数词

Number.prototype.ordinal = function () {
	return this + (
		(this % 10 == 1 && this % 100 != 11) ? 'st' :
		(this % 10 == 2 && this % 100 != 12) ? 'nd' :
		(this % 10 == 3 && this % 100 != 13) ? 'rd' : 'th'
	);
}

JavaScript moveCaret

function moveCaret(e, n) {
  e.selectionStart = e.selectionEnd = n;
}

JavaScript 搜索栏Google

<!-- Search Google -->
<center>
<form method="get" action="http://www.google.com/custom" target="google_window">
<table bgcolor="#ffffff">
<tr><td nowrap="nowrap" valign="top" align="left" height="32">
<a href="http://www.google.com/">
<img src="http://www.google.com/logos/Logo_25wht.gif" border="0" alt="Google" align="middle"></img></a>
<input type="text" name="q" size="35" maxlength="255" value=""></input>
<input type="submit" name="sa" value="Search"></input>
<input type="hidden" name="client" value="pub-1280039572425172"></input>
<input type="hidden" name="forid" value="1"></input>
<input type="hidden" name="channel" value="5016850435"></input>
<input type="hidden" name="ie" value="ISO-8859-1"></input>
<input type="hidden" name="oe" value="ISO-8859-1"></input>
<input type="hidden" name="safe" value="active"></input>
<input type="hidden" name="cof" value="GALT:#008000;GL:1;DIV:#336699;VLC:663399;AH:center;BGC:FFFFFF;LBGC:CCCCCC;ALC:0000FF;LC:0000FF;T:000000;GFNT:0000FF;GIMP:0000FF;LH:50;LW:190;L:http://www.cultivategreatness.com/images/cg_logo.gif;S:http://www.cultivategreatness.com;FORID:1"></input>
<input type="hidden" name="hl" value="en"></input>
</td></tr></table>
</form>
</center>
<!-- Search Google -->

JavaScript 调整弹出窗口大小以适合图像的大小

First of all you'll need one main HTML [1] page that will contain links to the full-sized pictures in your gallery:

<HTML>
 <HEAD>
   <TITLE>The Image Gallery</TITLE>
   <script language="Javascript [2]">
   function PopupPic(sPicURL) {
     window.open( "popup.htm?"+sPicURL, "",  
     "resizable=1,HEIGHT=200,WIDTH=200");
   }
   </script>
 </HEAD>
<BODY bgcolor="#FFFFFF">
   <a href="javascript:PopupPic('Image1.gif [3]')">Image 1</a><br>
   <a href="javascript:PopupPic('Image2.gif')">Image 2</a><br>
   <a href="javascript:PopupPic('Image3.gif')">Image 3</a><br>
</BODY>
</HTML>

Let's study the code above a little. We have a straightforward HTML page that contains a couple of links, and defines a simple Javascript function: PopupPic(). By clicking on any of the links on this page, you'll call the PopupPic() function. This function is really simple: the only thing it does is create a popup browser window, and load the popup.htm page in it.

The trick is that we pass the image's URL (relative to the image gallery Web page location) in the query string when the popup is created:

window.open( "popup.htm?"+sPicURL, "",  
"resizable=1,HEIGHT=200,WIDTH=200");

Now, take a look at the code of the popup.htm page:

<HTML>
<HEAD>
 <TITLE>Fit the Pic Script</TITLE>
 <script language='javascript'>
   var arrTemp=self.location.href.split("?");
   var picUrl = (arrTemp.length>0)?arrTemp[1]:"";
   var NS = (navigator.appName=="Netscape")?true:false;

     function FitPic() {
       iWidth = (NS)?window.innerWidth:document.body.clientWidth;
       iHeight = (NS)?window.innerHeight:document.body.clientHeight;
       iWidth = document.images[0].width - iWidth;
       iHeight = document.images[0].height - iHeight;
       window.resizeBy(iWidth, iHeight);
       self.focus();
     };
 </script>
</HEAD>
<BODY bgcolor="#000000" onload='FitPic();' topmargin="0"  
marginheight="0" leftmargin="0" marginwidth="0">
 <script language='javascript'>
 document.write( "<img src='" + picUrl + "' border=0>" );
 </script>
</BODY>
</HTML>

The first thing that should grab our attention is the fact that we're using Javascript code, which is directly executed while the page loads:

var arrTemp=self.location.href.split("?");
var picUrl = (arrTemp[1].length>0)?arrTemp[1]:"";
var NS = (navigator.appName=="Netscape")?true:false;

First, we get the page URL string and split it by the "?" character. The result of this split is held in the arrTemp array [4] variable.

On the second line we check if the second element of our temp array -- arrTemp[1] -- has length greater than 0, and if this is true, we assign the value of this second array element to the picURL variable.

On the third line we assign true to the NS variable if the browser is Netscape, otherwise we assign false. As you may already have guessed, the PicURL variable contains the relative URL of the picture that will be displayed in the popup.htm page.

After we have the PicURL variable, we can easily write the image into the document's body using document.write:

document.write( "<img src='" + picUrl + "' border=0>" );

After the page is completely loaded into the browser, the Load event is triggered and because we use onLoad event handler, the function FitPic() is called. The first 2 lines of this function find the browser's window width and height (depending on the browser). The next 3 lines however, are the most important lines in this function. Let's have a good look at them:

iWidth = document.images[0].width - iWidth;
iHeight = document.images[0].height - iHeight;
window.resizeBy(iWidth, iHeight);

After the page is fully loaded we can access the document's image collection, thus gaining access to the image properties. Because we have only one image on our page, and because the images collection is zero-based, the image is accessible [5] with document.images[0] -- this way, we can get image's width and height.

Then we subtract the initial browser width from the actual image width -- the result is a number by which the browser width has to be resized. We do the same with the initial browser height and the actual image height to ascertain the number of pixels by which we should resize the browser height in order to fit the picture.

The 3rd line is the actual resizing done by JavaScript's built in resizeBy() function. If you aren't familiar with the resizeBy() function, here's a short explanation.

By definition, this function resizes the current browser window by a certain amount. It takes 2 parameters: window.resizeBy(X, Y):

    * X - The number of pixels to grow the window horizontally
    * Y - The number of pixels to grow the window vertically

The following line shrinks the window's width by 10px and extends its height by 13px:

window.resizeBy(-10, +13);

The final line in our FitPic() function puts the focus on the popup.

So, to summarize how the script works, we pass the image-relative URL to the popup.htm (popup.htm?Images/Image1.gif), then we write the image tag into the body of the page with document.write, and when the page is loaded, we call FitPic(), which resizes the browser window to the image size.

JavaScript 随机数函数

function mran(ma,mi)
{return(Math.round(Math.random()*(ma-mi))+mi)}

JavaScript Cameron Adams的getBrowserWidth()

// getBrowserWidth() by Cameron Adams
// http://www.themaninblue.com/experiment/ResolutionLayout/
function getBrowserWidth ( ) {
    if ( window.innerWidth ) { return window.innerWidth; }
    else if ( document.documentElement && document.documentElement.clientWidth != 0 ) { return document.documentElement.clientWidth; }
    else if ( document.body ) { return document.body.clientWidth; }
    return 0;
}

JavaScript Paul Sowdon的setStyleSheet()

// setStyleSheet() by Paul Sowdon
// http://www.alistapart.com/articles/alternate/
function setStyleSheet ( title ) {
    var i, a, main;
    for ( i = 0; ( a = document.getElementsByTagName("link")[i] ); i++ ) {
        if ( a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") ) {
        a.disabled = true;
        if ( a.getAttribute("title") == title ) a.disaled = false;
        }
    }
}

JavaScript flashobject.js

/**
 * FlashObject v1.2.3: Flash detection and embed - http://blog.deconcept.com/flashobject/
 *
 * FlashObject is (c) 2005 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
if(typeof com == "undefined") var com = new Object();
if(typeof com.deconcept == "undefined") com.deconcept = new Object();
if(typeof com.deconcept.util == "undefined") com.deconcept.util = new Object();
if(typeof com.deconcept.FlashObjectUtil == "undefined") com.deconcept.FlashObjectUtil = new Object();
com.deconcept.FlashObject = function(swf, id, w, h, ver, c, useExpressInstall, quality, redirectUrl, detectKey){
   this.DETECT_KEY = detectKey ? detectKey : 'detectflash';
   this.skipDetect = com.deconcept.util.getRequestParameter(this.DETECT_KEY);
   this.params = new Object();
   this.variables = new Object();
   this.attributes = new Array();

   if(swf) this.setAttribute('swf', swf);
   if(id) this.setAttribute('id', id);
   if(w) this.setAttribute('width', w);
   if(h) this.setAttribute('height', h);
   if(ver) this.setAttribute('version', new com.deconcept.PlayerVersion(ver.toString().split(".")));
   if(c) this.addParam('bgcolor', c);
   var q = quality ? quality : 'high';
   this.addParam('quality', q);
   this.setAttribute('redirectUrl', '');
   if(redirectUrl) this.setAttribute('redirectUrl', redirectUrl);
   if(useExpressInstall) {
   // check to see if we need to do an express install
   var expressInstallReqVer = new com.deconcept.PlayerVersion([6,0,65]);
   var installedVer = com.deconcept.FlashObjectUtil.getPlayerVersion();
      if (installedVer.versionIsValid(expressInstallReqVer) && !installedVer.versionIsValid(this.getAttribute('version'))) {
         this.setAttribute('doExpressInstall', true);
      }
   } else {
      this.setAttribute('doExpressInstall', false);
   }
}
com.deconcept.FlashObject.prototype.setAttribute = function(name, value){
	this.attributes[name] = value;
}
com.deconcept.FlashObject.prototype.getAttribute = function(name){
	return this.attributes[name];
}
com.deconcept.FlashObject.prototype.getAttributes = function(){
	return this.attributes;
}
com.deconcept.FlashObject.prototype.addParam = function(name, value){
	this.params[name] = value;
}
com.deconcept.FlashObject.prototype.getParams = function(){
	return this.params;
}
com.deconcept.FlashObject.prototype.getParam = function(name){
	return this.params[name];
}
com.deconcept.FlashObject.prototype.addVariable = function(name, value){
	this.variables[name] = value;
}
com.deconcept.FlashObject.prototype.getVariable = function(name){
	return this.variables[name];
}
com.deconcept.FlashObject.prototype.getVariables = function(){
	return this.variables;
}
com.deconcept.FlashObject.prototype.getParamTags = function(){
   var paramTags = ""; var key; var params = this.getParams();
   for(key in params) {
        paramTags += '<param name="' + key + '" value="' + params[key] + '" />';
    }
   return paramTags;
}
com.deconcept.FlashObject.prototype.getVariablePairs = function(){
	var variablePairs = new Array();
	var key;
	var variables = this.getVariables();
	for(key in variables){
		variablePairs.push(key +"="+ variables[key]);
	}
	return variablePairs;
}
com.deconcept.FlashObject.prototype.getHTML = function() {
    var flashHTML = "";
    if (navigator.plugins && navigator.mimeTypes && navigator.mimeTypes.length) { // netscape plugin architecture
        if (this.getAttribute("doExpressInstall")) { this.addVariable("MMplayerType", "PlugIn"); }
        flashHTML += '<embed type="application/x-shockwave-flash" src="'+ this.getAttribute('swf') +'" width="'+ this.getAttribute('width') +'" height="'+ this.getAttribute('height') +'" id="'+ this.getAttribute('id') + '" name="'+ this.getAttribute('id') +'"';
		var params = this.getParams();
        for(var key in params){ flashHTML += ' '+ key +'="'+ params[key] +'"'; }
		pairs = this.getVariablePairs().join("&");
        if (pairs.length > 0){ flashHTML += ' flashvars="'+ pairs +'"'; }
        flashHTML += '></embed>';
    } else { // PC IE
        if (this.getAttribute("doExpressInstall")) { this.addVariable("MMplayerType", "ActiveX"); }
        flashHTML += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+ this.getAttribute('width') +'" height="'+ this.getAttribute('height') +'" id="'+ this.getAttribute('id') +'">';
        flashHTML += '<param name="movie" value="' + this.getAttribute('swf') + '" />';
		var tags = this.getParamTags();
        if(tags.length > 0){ flashHTML += tags; }
		var pairs = this.getVariablePairs().join("&");
        if(pairs.length > 0){ flashHTML += '<param name="flashvars" value="'+ pairs +'" />'; }
        flashHTML += '</object>';
    }
    return flashHTML;
}
com.deconcept.FlashObject.prototype.write = function(elementId){
	if(this.skipDetect || this.getAttribute('doExpressInstall') || com.deconcept.FlashObjectUtil.getPlayerVersion().versionIsValid(this.getAttribute('version'))){
		if(document.getElementById){
		   if (this.getAttribute('doExpressInstall')) {
		      this.addVariable("MMredirectURL", escape(window.location));
		      document.title = document.title.slice(0, 47) + " - Flash Player Installation";
		      this.addVariable("MMdoctitle", document.title);
		   }
			document.getElementById(elementId).innerHTML = this.getHTML();
		}
	}else{
		if(this.getAttribute('redirectUrl') != "") {
			document.location.replace(this.getAttribute('redirectUrl'));
		}
	}
}
/* ---- detection functions ---- */
com.deconcept.FlashObjectUtil.getPlayerVersion = function(){
   var PlayerVersion = new com.deconcept.PlayerVersion(0,0,0);
	if(navigator.plugins && navigator.mimeTypes.length){
		var x = navigator.plugins["Shockwave Flash"];
		if(x && x.description) {
			PlayerVersion = new com.deconcept.PlayerVersion(x.description.replace(/([a-z]|[A-Z]|\s)+/, "").replace(/(\s+r|\s+b[0-9]+)/, ".").split("."));
		}
	}else if (window.ActiveXObject){
	   try {
   	   var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
   		PlayerVersion = new com.deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));
	   } catch (e) {}
	}
	return PlayerVersion;
}
com.deconcept.PlayerVersion = function(arrVersion){
	this.major = parseInt(arrVersion[0]) || 0;
	this.minor = parseInt(arrVersion[1]) || 0;
	this.rev = parseInt(arrVersion[2]) || 0;
}
com.deconcept.PlayerVersion.prototype.versionIsValid = function(fv){
	if(this.major < fv.major) return false;
	if(this.major > fv.major) return true;
	if(this.minor < fv.minor) return false;
	if(this.minor > fv.minor) return true;
	if(this.rev < fv.rev) return false;
	return true;
}
/* ---- get value of query string param ---- */
com.deconcept.util.getRequestParameter = function(param){
	var q = document.location.search || document.location.href.hash;
	if(q){
		var startIndex = q.indexOf(param +"=");
		var endIndex = (q.indexOf("&", startIndex) > -1) ? q.indexOf("&", startIndex) : q.length;
		if (q.length > 1 && startIndex > -1) {
			return q.substring(q.indexOf("=", startIndex)+1, endIndex);
		}
	}
	return "";
}

/* add Array.push if needed (ie5) */
if (Array.prototype.push == null) { Array.prototype.push = function(item) { this[this.length] = item; return this.length; }}

/* add some aliases for ease of use / backwards compatibility */
var getQueryParamValue = com.deconcept.util.getRequestParameter;
var FlashObject = com.deconcept.FlashObject;

JavaScript 添加Flash

function addFlashObj(node, swf) {
	var o = document.createElement('object');
	node.appendChild(o);
	var p = document.createElement('param');
	p.setAttribute('name', 'movie');
	p.setAttribute('value', swf);
	o.appendChild(p);
	o.setAttribute('data', swf);
	o.setAttribute('type', 'application/x-shockwave-flash');
}

addFlashObj(document.body, 'sample.swf');