JavaScript 使用jQuery预加载图像

<script type="text/javascript" charset="utf-8">
	// JQUERY WAY TO PRELOAD IMAGES
	// DOES NOT NEED TO BE IN DOCUMENT READY
	$.preloadImages = function()
	{
	        for(var i = 0; i<arguments.length; i++)
	        {
	                img = new Image();
	                img.src = arguments[i];
	        }

	}
	$.preloadImages(
	"path/to/image/1",
	"path/to/image/2",
	"path/to/image/3"
	);
</script>

JavaScript 从Google CDN加载jQuery,但如果失败则回退到本地

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

<script type="text/javascript">
if (typeof jQuery == 'undefined')
{
    document.write(unescape("%3Cscript src='/path/to/your/jquery' type='text/javascript'%3E%3C/script%3E"));
}
</script>

JavaScript 对Internet Explorer的PNG Opacity支持(简化)

//	this script have dependencies on prototype-1.4.0.js and Browser Detect Lite  v2.1
//	http://prototype.conio.net/
//	http://www.dithered.com/javascript/browser_detect/index.html
//	(cc) alvaro isorna

Event.observe(window, 'load', function(){
	//	this will iterate with each element with the class 'ie-fix-opacity' and add an IE filter,
	//	replacing the background-image for the filter of that image
	document.getElementsByClassName('ie-fix-opacity').each(function(poElement){
		// if IE5.5+ on win32, then display PNGs with AlphaImageLoader
		if ((browser.isIE55 || browser.isIE6up) && browser.isWin32){
			var cBGImg = poElement.currentStyle.backgroundImage;
			var cImage = cBGImg.substring(cBGImg.indexOf('"') + 1, cBGImg.lastIndexOf('"'));
					
			poElement.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + cImage + "', sizingMethod='scale')";
			poElement.style.backgroundImage = "none";
		}
	});
}, false);

JavaScript javascript cookies

/**
 * Sets a Cookie with the given name and value.
 *
 * name       Name of the cookie
 * value      Value of the cookie
 * [expires]  Expiration date of the cookie (default: end of current session)
 * [path]     Path where the cookie is valid (default: path of calling document)
 * [domain]   Domain where the cookie is valid
 *              (default: domain of calling document)
 * [secure]   Boolean value indicating if the cookie transmission requires a
 *              secure transmission
 */
function setCookie(name, value, expires, path, domain, secure) {
    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

/**
 * Gets the value of the specified cookie.
 *
 * name  Name of the desired cookie.
 *
 * Returns a string containing value of specified cookie,
 *   or null if cookie does not exist.
 */
function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

/**
 * Deletes the specified cookie.
 *
 * name      name of the cookie
 * [path]    path of the cookie (must be same as path used to create cookie)
 * [domain]  domain of the cookie (must be same as domain used to create cookie)
 */
function deleteCookie(name, path, domain) {
    if (getCookie(name)) {
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

JavaScript HTTP请求

// ----------------------------------------
// Wrapper function for constructing a request object.
//	Parameters:
//		reqType: The HTTP request type, such as GET or POST.
//		url: The URL of the server program.
//		asynch: Whether to send the request asynchronously or not.
// ----------------------------------------

function httpRequest(reqType,url,asynch) {

	// Mozilla-based browsers
	if (window.XMLHttpRequest) {
		request = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		request = new ActiveXObject("Msxml2.XMLHTTP");
		if (!request) {
			request = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	
	// Request could still be null if neither ActiveXObject
	//   initialization succeeded
	if (request) {
		// If the reqType param is POST, then the fifth arg is the POSTed data
		if (reqType.toLowerCase() != "post") {
			initReq(reqType, url, asynch, respHandle);
		} else {
			// The POSTed data
			var args = arguments[4];
			if (args != null && args.length > 0) {
				initReq(reqType, url, asynch, respHandle, args);
			}
		}
	} else {
		alert("Your browser does not permit the use of all " +
			"of this application's features!");
	}

}

// ----------------------------------------
// Initialize a request object that is already constructed
// ----------------------------------------

function initReq(reqType, url, bool, respHandle) {
	try {
		// Specify the function that will handle the HTTP response
		request.onreadystatechange = handleResponse;
		request.open(reqType, url, bool);
		// If the reqType param is POST, then the
		//   fifth argument to the function is the POSTed data
		if (reqType.toLowerCase() == "post") {
			// Set the Content-Type header for a POST request
			request.setRequestHeader("Content-Type", "application/x-ww-form-urlencoded; charset=UTF-8");
			request.send(arguments[4]);
		} else {
			request.send(null);
		}
	} catch (errv) {
		alert("The application cannot contact the server at the moment. " +
			"Please try again in a few seconds.\n" +
			"Error detail: " errv.message);
	}
}

JavaScript 渐变类

/**
	@author		Jeremy M. Daley
	@company	HSR Business to Business
	@title		Web Application Developer
	@email		daleyjem@yahoo.com
*/

/**
	Apply a Top-Bottom or Left-Right gradient (with or without alpha transparency)
	by attaching a "gradient" class to any HTML element. Does not interfere with existing classes
	on element.
	
	Usage:
		<div class="some_existing_class gradient(#rrggbb[aa], #rrggbb[aa][, gradient_direction])">Some Text</div>
		
		@param	color1				= hex rgba color value (alpha hex value optional)
		@param	color2				= hex rgba color value (alpha hex value optional)
		@param	gradient_direction	= (optional) linear direction of gradient transition ("tb" or "lr"). 
									  defaults to "tb" if not specified
		
	Example: 
		gradient(#ffffffff, #00000000, tb)
			
		->	Applies a Top-Bottom gradient with the first color value
			a full-opacity white, and the second color value
			a full-transparency black
		
*/

if (window.addEventListener) {
	window.addEventListener("load", initGradient, false);
} else {
	window.attachEvent("onload", initGradient);
}

var currZ = 1;

function initGradient() {
	var DOM = document.getElementsByTagName("*");
	
	for (var elementIndex = 0; elementIndex < DOM.length; elementIndex++) {
		var theElement		= DOM[elementIndex];
		var elementClass	= theElement.className;
		
		if (elementClass.toLowerCase().indexOf("gradient(") != -1) {
			createGradient(theElement);
		}
		
	}
	
}

function createGradient(gradElement) {
	var divClass	= gradElement.className;
	var pos			= divClass.toLowerCase().indexOf("gradient(");
	var tempStr		= divClass.substr(pos);
	var pos1		= tempStr.indexOf("(");
	var pos2		= tempStr.indexOf(")");
	tempStr			= tempStr.substr(pos1 + 1, pos2 - pos1 - 1);
	
	var paramArray	= tempStr.split(",");
	var gradStyle	= (paramArray.length > 2) ? paramArray[2].toUpperCase().replace(/ /g, "") : "TB";
	var startHex	= paramArray[0].replace("#", "").replace(" ", "");
	var endHex		= paramArray[1].replace("#", "").replace(" ", "");
	var startAlpha	= (startHex.length > 6) ? startHex.substr(6, 2) : "FF";
	var endAlpha	= (endHex.length > 6) ? endHex.substr(6, 2) : "FF";

	var startR	= parseInt(startHex.substr(0, 2), 16);
	var startG	= parseInt(startHex.substr(2, 2), 16);
	var startB	= parseInt(startHex.substr(4, 2), 16);
	var startA	= Math.round((parseInt(startAlpha, 16) * 100) / 255);
	var endR	= parseInt(endHex.substr(0, 2), 16);
	var endG	= parseInt(endHex.substr(2, 2), 16);
	var endB	= parseInt(endHex.substr(4, 2), 16);
	var endA	= Math.round((parseInt(endAlpha, 16) * 100) / 255);
	
	var pullHTML = gradElement.innerHTML;
	
	if (gradElement.style.position.toLowerCase() != "absolute") {
		gradElement.style.position = "relative";
	}
	
	var borderWidth		= parseInt(gradElement.style.borderRightWidth) + parseInt(gradElement.style.borderLeftWidth);
	var borderHeight	= parseInt(gradElement.style.borderTopWidth) + parseInt(gradElement.style.borderBottomWidth);
	var theWidth		= gradElement.offsetWidth - ((isNaN(borderWidth)) ? 0 : borderWidth);
	var theHeight		= gradElement.offsetHeight - ((isNaN(borderHeight)) ? 0 : borderHeight);

	var stringArray = [];
	
	/**
		Note:	- 	<table>'s are used for cross-browser and W3C compliance. Using <div>'s breaks in IE
					(can't insert <div> as child of <p>). <table>'s retain abiguity for inserting into <p> tags
				- 	<span> tags don't handle z-index correctly in Opera
				
	*/
	stringArray.push('<table width="100%" border="0" cellpadding="0" cellspacing="0" style="position:absolute; left:0px; top:0px; z-index:' + currZ + '"><tr><td>');
	var gradIndex = (gradStyle == "TB") ? theHeight : theWidth;

	for (var divIndex = 0; divIndex < gradIndex; divIndex++) {
		var valPerc = divIndex / gradIndex;
		var newR 		= startR - (Math.ceil((startR - endR) * valPerc));
		var newG		= startG - (Math.ceil((startG - endG) * valPerc));
		var newB		= startB - (Math.ceil((startB - endB) * valPerc));
		var newA		= startA - (Math.ceil((startA - endA) * valPerc));
		var newWidth	= (gradStyle == "TB") ? theWidth : 1;
		var newHeight	= (gradStyle == "TB") ? 1 : theHeight;
		var newTop		= (gradStyle == "TB") ? divIndex : 0;
		var newLeft		= (gradStyle == "TB") ? 0 : divIndex;
		
		/* using span inside span method */
		stringArray.push('<table width="100%" border="0" cellpadding="0" cellspacing="0" style="position:absolute; top:' + newTop + 'px; left:' + newLeft + 'px; opacity:' + (newA / 100) + '; -moz-opacity:' + (newA / 100) + '; filter:alpha(opacity=' + newA + '); width:' + newWidth + 'px; height:' + newHeight + 'px; background-color:rgb(' + newR + ',' + newG + ',' + newB + '); "><tr><td><div style="position:absolute; width:1px; height:1px; "></div></td></tr></table>');
	}
	
	stringArray.push('</table>');
	stringArray.push('<table width="100%" border="0" cellpadding="0" cellspacing="0" style="position:relative; z-index:' + (currZ + 1) + '; "><tr><td>' + pullHTML + '</td></tr></table>');
	var writeStr = stringArray.join("");
	gradElement.innerHTML = writeStr;
	
	currZ += 2;
}

JavaScript jquery firebug日志

jQuery.fn.log = function (msg) {
    console.log("%s: %o", msg, this);
    return this;
};

JavaScript jQuery下拉导航

$(document).ready(function() {
//Main nav drop-downs
  $('#header ul li').each(function() {
    $(this).mouseover(function() {
      $(this).children('ul').css("display", "block");
    });
    $(this).mouseout(function() {
      $(this).children('ul').css("display", "none");
    });
  });
});

JavaScript 确定浏览器是否理解HTML5视频

// Check if the browser understands the video element.
function understands_video() {
  return !!document.createElement('video').canPlayType; // boolean
}

if ( !understands_video() ) { 
	// Must be older browser or IE. 
	// Maybe do something like hide custom
	// HTML5 controls. Or whatever...
	videoControls.style.display = 'none';
}

JavaScript 使用计时器重定向

<script type="text/javascript">
var count = 6;
var redirect = "http://www.apphp.com";
 
function countDown(){
    var timer = document.getElementById("timer");
    if(count > 0){
        count--;
        timer.innerHTML = "This page will redirect in "+count+" seconds.";
        setTimeout("countDown()", 1000);
    }else{
        window.location.href = redirect;
    }
}
</script>
 
Our webpage has beed moved. Please update your bookmarks for the new site.
<br>
 
<span id="timer">
<script type="text/javascript">countDown();</script>
</span>