JavaScript 扩大形式

expanding forms

JavaScript Comprobar si un combotienealgúnvalorseleccionado

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Documento sin título</title>
</head>
<script>
function prueba(){
 
 for (var i = 0; i < document.form.combo.options.length; i++) {  
  if (document.form.combo.options [i].selected && document.form.combo.options[i].value!='')     
   document.write( document.form.combo.options[i].value)
 }
}
</script>
<body>
<form name="form">
 <select name="combo">
  <option value=""></option>
  <option value="a">a</option>
  <option value="b">b</option>
  <option value="c">c</option>
 </select>
 <input type="button" onClick="prueba();">
</form>
</body>
</html>

JavaScript Javascript浏览器检测精简版

// JavaScript Document
// if IE5.5+ on Win32, then display PNGs with AlphaImageLoader
var pngAlpha
var pngNormal
//var browser = this.browser();
// Browser Detect Lite  v2.1
// http://www.dithered.com/javascript/browser_detect/index.html
// modified by Chris Nott (chris@NOSPAMdithered.com - remove NOSPAM)
//
// modified by Michael Lovitt to include OmniWeb and Dreamcast

function BrowserDetectLite() {
	var ua = navigator.userAgent.toLowerCase(); 
	this.ua = ua;

	// browser name
	this.isGecko     = (ua.indexOf('gecko') != -1);
	this.isMozilla   = (this.isGecko && ua.indexOf("gecko/") + 14 == ua.length);
	this.isNS        = ( (this.isGecko) ? (ua.indexOf('netscape') != -1) : ( (ua.indexOf('mozilla') != -1) && (ua.indexOf('spoofer') == -1) && (ua.indexOf('compatible') == -1) && (ua.indexOf('opera') == -1) && (ua.indexOf('webtv') == -1) && (ua.indexOf('hotjava') == -1) ) );
	this.isIE        = ( (ua.indexOf("msie") != -1) && (ua.indexOf("opera") == -1) && (ua.indexOf("webtv") == -1) ); 
	this.isOpera     = (ua.indexOf("opera") != -1); 
	this.isKonqueror = (ua.indexOf("konqueror") != -1); 
	this.isIcab      = (ua.indexOf("icab") != -1); 
	this.isAol       = (ua.indexOf("aol") != -1); 
	this.isWebtv     = (ua.indexOf("webtv") != -1); 
	this.isOmniweb   = (ua.indexOf("omniweb") != -1);
	this.isDreamcast   = (ua.indexOf("dreamcast") != -1);
	
	// spoofing and compatible browsers
	this.isIECompatible = ( (ua.indexOf("msie") != -1) && !this.isIE);
	this.isNSCompatible = ( (ua.indexOf("mozilla") != -1) && !this.isNS && !this.isMozilla);
	
	// browser version
	this.versionMinor = parseFloat(navigator.appVersion); 
	
	// correct version number for NS6+ 
	if (this.isNS && this.isGecko) {
		this.versionMinor = parseFloat( ua.substring( ua.lastIndexOf('/') + 1 ) );
	}
	
	// correct version number for IE4+ 
	else if (this.isIE && this.versionMinor >= 4) {
		this.versionMinor = parseFloat( ua.substring( ua.indexOf('msie ') + 5 ) );
	}
	
	// correct version number for Opera 
	else if (this.isOpera) {
		if (ua.indexOf('opera/') != -1) {
			this.versionMinor = parseFloat( ua.substring( ua.indexOf('opera/') + 6 ) );
		}
		else {
			this.versionMinor = parseFloat( ua.substring( ua.indexOf('opera ') + 6 ) );
		}
	}
	
	// correct version number for Konqueror
	else if (this.isKonqueror) {
		this.versionMinor = parseFloat( ua.substring( ua.indexOf('konqueror/') + 10 ) );
	}
	
	// correct version number for iCab 
	else if (this.isIcab) {
		if (ua.indexOf('icab/') != -1) {
			this.versionMinor = parseFloat( ua.substring( ua.indexOf('icab/') + 6 ) );
		}
		else {
			this.versionMinor = parseFloat( ua.substring( ua.indexOf('icab ') + 6 ) );
		}
	}
	
	// correct version number for WebTV
	else if (this.isWebtv) {
		this.versionMinor = parseFloat( ua.substring( ua.indexOf('webtv/') + 6 ) );
	}
	
	this.versionMajor = parseInt(this.versionMinor); 
	this.geckoVersion = ( (this.isGecko) ? ua.substring( (ua.lastIndexOf('gecko/') + 6), (ua.lastIndexOf('gecko/') + 14) ) : -1 );
	
	// platform
	this.isWin   = (ua.indexOf('win') != -1);
	this.isWin32 = (this.isWin && ( ua.indexOf('95') != -1 || ua.indexOf('98') != -1 || ua.indexOf('nt') != -1 || ua.indexOf('win32') != -1 || ua.indexOf('32bit') != -1) );
	this.isMac   = (ua.indexOf('mac') != -1);
	this.isUnix  = (ua.indexOf('unix') != -1 || ua.indexOf('linux') != -1 || ua.indexOf('sunos') != -1 || ua.indexOf('bsd') != -1 || ua.indexOf('x11') != -1)
	
	// specific browser shortcuts
	this.isNS4x = (this.isNS && this.versionMajor == 4);
	this.isNS40x = (this.isNS4x && this.versionMinor < 4.5);
	this.isNS47x = (this.isNS4x && this.versionMinor >= 4.7);
	this.isNS4up = (this.isNS && this.versionMinor >= 4);
	this.isNS6x = (this.isNS && this.versionMajor == 6);
	this.isNS6up = (this.isNS && this.versionMajor >= 6);
	
	this.isIE4x = (this.isIE && this.versionMajor == 4);
	this.isIE4up = (this.isIE && this.versionMajor >= 4);
	this.isIE5x = (this.isIE && this.versionMajor == 5);
	this.isIE55 = (this.isIE && this.versionMinor == 5.5);
	this.isIE5up = (this.isIE && this.versionMajor >= 5);
	this.isIE6x = (this.isIE && this.versionMajor == 6);
	this.isIE6up = (this.isIE && this.versionMajor >= 6);
	
	this.isIE4xMac = (this.isIE4x && this.isMac);
}
var browser = new BrowserDetectLite();

JavaScript 从一次点击弹出一个元素

function popup() {
	var id = document.getElementById(ID);
	var screenW = document.body.clientWidth;
	id.style.left = (screenW - 850)/2 + 515 + "px";
	if (id.style.display == "none") {
		id.style.display = "block";
	}
	else {
		id.style.display = "none";
	}
}

JavaScript Javascript - 翻转con预览immagine

var t_id = setInterval(animate,20);
var pos=0;
var dir=2;
var len=0;

function animate()
{
var elem = document.getElementById('progress');
if(elem != null) {
if (pos==0) len += dir;
if (len>32 || pos>79) pos += dir;
if (pos>79) len -= dir;
if (pos>79 && len==0) pos=0;
elem.style.left = pos;
elem.style.width = len;
}
}

function remove_loading() {
this.clearInterval(t_id);
var targelem = document.getElementById('loader_container');
targelem.style.display='none';
targelem.style.visibility='hidden';
var t_id = setInterval(animate,60);
}


var offsetfrommouse=[15,25]; //image x,y offsets from cursor position in pixels. Enter 0,0 for no offset
var displayduration=0; //duration in seconds image should remain visible. 0 for always.

var defaultimageheight = 40;	// maximum image size.
var defaultimagewidth = 40;	// maximum image size.

var timer;

function gettrailobj(){
if (document.getElementById)
return document.getElementById("preview_div").style
}

function gettrailobjnostyle(){
if (document.getElementById)
return document.getElementById("preview_div")
}


function truebody(){
return (!window.opera && document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}


function hidetrail(){	
	gettrailobj().display= "none";
	document.onmousemove=""
	gettrailobj().left="-500px"
	clearTimeout(timer);
}

function showtrail(imagename,title,width,height){
	i = imagename
	t = title
	w = width
	h = height
	timer = setTimeout("show('"+i+"',t,w,h);",200);
}
function show(imagename,title,width,height){
 
    var docwidth=document.all? truebody().scrollLeft+truebody().clientWidth : pageXOffset+window.innerWidth - offsetfrommouse[0]
	var docheight=document.all? Math.min(truebody().scrollHeight, truebody().clientHeight) : Math.min(window.innerHeight)

	if( (navigator.userAgent.indexOf("Konqueror")==-1  || navigator.userAgent.indexOf("Firefox")!=-1 || (navigator.userAgent.indexOf("Opera")==-1 && navigator.appVersion.indexOf("MSIE")!=-1)) && (docwidth>650 && docheight>500)) {
		( width == 0 ) ? width = defaultimagewidth: '';
		( height == 0 ) ? height = defaultimageheight: '';
			
		width+=30
		height+=55
		defaultimageheight = height
		defaultimagewidth = width
	
		document.onmousemove=followmouse; 

		
		newHTML = '<div class="border_preview" style="width:'+  width +'px;height:'+ height +'px"><div id="loader_container"><div id="loader"><div align="center">Loading template preview...</div><div id="loader_bg"><div id="progress"> </div></div></div></div>';
		newHTML = newHTML + '<h2 class="title_h2">' + ' '+title + '</h2>'
		
    	newHTML = newHTML + '<div class="preview_temp_load"><img onload="javascript:remove_loading();" src="' + imagename + '" border="0"></div>';
		newHTML = newHTML + '</div>'; 
		
		if(navigator.userAgent.indexOf("MSIE")!=-1 && navigator.userAgent.indexOf("Opera")==-1 ){
			newHTML = newHTML+'<iframe src="about:blank" scrolling="no" frameborder="0" width="'+width+'" height="'+height+'"></iframe>';
		}		

		gettrailobjnostyle().innerHTML = newHTML;
		gettrailobj().display="block";
	}
}

function followmouse(e){

	var xcoord=offsetfrommouse[0]
	var ycoord=offsetfrommouse[1]

	var docwidth=document.all? truebody().scrollLeft+truebody().clientWidth : pageXOffset+window.innerWidth-15
	var docheight=document.all? Math.min(truebody().scrollHeight, truebody().clientHeight) : Math.min(window.innerHeight)

	if (typeof e != "undefined"){
		if (docwidth - e.pageX < defaultimagewidth + 2*offsetfrommouse[0]){
			xcoord = e.pageX - xcoord - defaultimagewidth; // Move to the left side of the cursor
		} else {
			xcoord += e.pageX;
		}
		if (docheight - e.pageY < defaultimageheight + 2*offsetfrommouse[1]){
			ycoord += e.pageY - Math.max(0,(2*offsetfrommouse[1] + defaultimageheight + e.pageY - docheight - truebody().scrollTop));
		} else {
			ycoord += e.pageY;
		}

	} else if (typeof window.event != "undefined"){
		if (docwidth - event.clientX < defaultimagewidth + 2*offsetfrommouse[0]){
			xcoord = event.clientX + truebody().scrollLeft - xcoord - defaultimagewidth; // Move to the left side of the cursor
		} else {
			xcoord += truebody().scrollLeft+event.clientX
		}
		if (docheight - event.clientY < (defaultimageheight + 2*offsetfrommouse[1])){
			ycoord += event.clientY + truebody().scrollTop - Math.max(0,(2*offsetfrommouse[1] + defaultimageheight + event.clientY - docheight));
		} else {
			ycoord += truebody().scrollTop + event.clientY;
		}
	}
	gettrailobj().left=xcoord+"px"
	gettrailobj().top=ycoord+"px"

}


<html>
	<head>
		<script src="preview_templates.js" language="JavaScript" type="text/javascript"></script>
		<script src="loader.js" language="JavaScript" type="text/javascript"></script>
	</head>

	<body>
		<img src="uno.jpg" border=0  border=1 style="border-color: 777777" onmouseover="showtrail('due.jpg ','Template 12306',430,449);"   onmouseout="hidetrail();">
		<div style="display: none; position: absolute;z-index:110; " id="preview_div"></div>
	</body>
</html>

JavaScript JavaScript - 简单示例Istogramma

function istogramma()
{
	/*
	 *
	 * Prende in input una serie di numeri, sia positivi che negativi
	 * e crea un istogramma. 
	 */
	 	
	var n = window.prompt('Numero di valori da inserire:', '');
	
	n = parseInt(n); // rende il valore se valido Int altrimenti NaN
	
	if(isNaN(n) == true)
	{
		document.write('<p align=\"center\"><b>Non hai selezionato nessun valore...</b></p>');
		document.write('<br>');
	}
	else
	{
		var num = new Array();
		var max = 0;
		
		for(var i=0; i<n; i++)
		{
			var tmp = window.prompt('Inserire Valore [' + (i+1) + '/' + n + ']', '');
			tmp = parseFloat(tmp);
			
			if(isNaN(tmp) == true)
			{
				n = i;
				break;
			}
			
			num[i] = tmp;
			
			if(max < Math.abs(num[i])) max = Math.abs(num[i]);
		}
		
		for(var i=0; i<n; i++) num[i] *= 100/max;
		
		document.write('<p align=\"center\"><b>Istogramma for JavaScript</b></p>');
		document.write('<br>');
		document.write('<table align=\"center\" border=\"0\" bgcolor=\"red\">');
		document.write('<tr><td>');
		document.write('<table align=\"center\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" width=\"200\" bgcolor=\"black\">');

		for(var j=0; j<n; j++)
		{
			document.write('<tr>');
			
			for(var i=0; i<200; i++)
			{
				var aux = num[j];
				
				if(num[j] == 0) document.write('<td width=\"1\" bgcolor=\"white\"> </td>');
				
				if(num[j] > 0 && i < 100) document.write('<td width=\"1\" bgcolor=\"white\"> </td>');
				else if(num[j] > 0 && i >= 100)
				{
					if((i-100) <= aux)
						document.write('<td width=\"1\" bgcolor=\"green\"> </td>');
					else
						document.write('<td width=\"1\" bgcolor=\"white\"> </td>');
				}
				
				if(num[j] < 0 && i < (100+aux)) document.write('<td width=\"1\" bgcolor=\"white\"> </td>');
				else if(num[j] < 0 && (i >= (100+aux) && i < 100)) document.write('<td width=\"1\" bgcolor=\"yellow\"> </td>');
				else if(num[j] < 0 && i >= 100) document.write('<td width=\"1\" bgcolor=\"white\"> </td>');
			}
			
			document.write('</tr>');
		}

		document.write('</table>');
		document.write('</td></tr>');
		document.write('</table>');
	}
}


<html>
	<head>
		<title>Disegnare un Istogramma...</title>
		<script src='istogramma.js' type='text/javascript'></script>
	</head>
	
	<body OnLoad="istogramma();">
	</body>
</html>

JavaScript OPML PopUp可以简化Podcast聚合

/* 'Get Podcasts'
* if isOPML is false, it pops up an escaped version in HTML.
* if isOPML is true, it pops up an OPML version.
* Either way, you need to copy and save the results as a file with an .opml extension
* You can then add it to your Aggregator of choice:
*/

var isOPML=false;
var entry=document.getElementById('entry-14040355');
var ul=entry.getElementsByTagName('ul')[1];
var links=ul.getElementsByTagName('a');
var smalls=entry.getElementsByTagName('small');
var names=[];var cond=false;var text=url=title="";
for(var i=0;i<smalls.length;++i){
	cond=false;text=smalls[i].childNodes[0].nodeValue;
	for(var j=0;j<names.length;++j){
		if(text==names[j]){
			cond=true;
		}
	}
	if(!cond){
		names.push(text);
	}
}
//So far, names=["Purdue University","Southwest Tech","Berkeley","College of St. Scholastica","John Hopkins University","UCLA","Western Kentucky University","College of DuPage","NC State University","City University of New York","Ohio State University"];
function filter(name){
	var t=output="";
	for(var k=0;k<links.length;++k){
		t=smalls[k].childNodes[0].nodeValue;
		if(t==name){
			url=links[k].href;
			title=links[k].childNodes[0].nodeValue;
			output=output+'			<outline text="'+title+'" title="'+title+'" type="rss" xmlUrl="'+url+'" htmlUrl="'+url+'"/>'+"\n";
		}
	}
	return output;
}
var header='<opml version="1.0">'+"\n"+'	<head>'+"\n"+'		<title>Free Academic Podcasts</title>'+"\n"+'	</head>'+"\n"+'	<body>'+"\n";
var body='';
names.sort();
var p='Choose from which university you would like to get the podcasts from:\n 0. All';
for(var l=0;l<names.length;++l){
	p=p+'\n '+(l+1)+'. '+names[l];
}
var reply=prompt(p,"");
var choice=parseInt(reply)-1;
if(choice<0||choice>names.length-1||isNaN(choice)){
	for(var l=0;l<names.length;++l){
		body=body+'		<outline title="'+names[l]+'" text="'+names[l]+'">'+"\n"+filter(names[l])+'		</outline>'+"\n";
	}
}else{
	body='		<outline title="'+names[choice]+'" text="'+names[choice]+'">'+"\n"+filter(names[choice])+'		</outline>'+"\n";
}
body=body.replace(/="\s/g,'="');
body=body.replace(/&/g,'&');
var footer='	</body>'+"\n"+'</opml>';
var htmlHeader='<html><head><title>Free Academic Podcasts</title></head><body>';
var htmlFooter='</body></html>';
var opml=(isOPML)?header+body+footer:htmlHeader+(((((header+body+footer).replace(/&/g,'&')).replace(/>/g,'>')).replace(/</g,'<')).replace(/\n/g,'<br>\n'))+htmlFooter;
function popOPML(code){
	var gOPML=window.open('','Free Academic Podcasts','top=300,left=200,height=480,width=640');
	var tmp=gOPML.document;
	tmp.open();
	tmp.write(code);
	tmp.close();
}
popOPML(opml);

/*Resulting Bookmarklet:*/
/*javascript:(function(){var%20isOPML=false;var%20entry=document.getElementById('entry-14040355');var%20ul=entry.getElementsByTagName('ul')[1];var%20links=ul.getElementsByTagName('a');var%20smalls=entry.getElementsByTagName('small');var%20names=[];var%20cond=false;var%20text=url=title='';for(var%20i=0;i<smalls.length;++i){cond=false;text=smalls[i].childNodes[0].nodeValue;for(var%20j=0;j<names.length;++j){if(text==names[j]){cond=true}}if(!cond){names.push(text)}}function%20filter(name){var%20t=output='';for(var%20k=0;k<links.length;++k){t=smalls[k].childNodes[0].nodeValue;if(t==name){url=links[k].href;title=links[k].childNodes[0].nodeValue;output=output+'			<outline%20text=%22'+title+'%22%20title=%22'+title+'%22%20type=%22rss%22%20xmlUrl=%22'+url+'%22%20htmlUrl=%22'+url+'%22/>'+%22\n%22}}return%20output}var%20header='<opml%20version=%221.0%22>'+%22\n%22+'	<head>'+%22\n%22+'		<title>Free%20Academic%20Podcasts</title>'+%22\n%22+'	</head>'+%22\n%22+'	<body>'+%22\n%22;var%20body='';names.sort();var%20p='Choose%20from%20which%20university%20you%20would%20like%20to%20get%20the%20podcasts%20from:\n%200.%20All';for(var%20l=0;l<names.length;++l){p=p+'\n%20'+(l+1)+'.%20'+names[l];}var%20reply=prompt(p,%22%22);var%20choice=parseInt(reply)-1;if(choice<0||choice>names.length-1||isNaN(choice)){for(var%20l=0;l<names.length;++l){body=body+'		<outline%20title=%22'+names[l]+'%22%20text=%22'+names[l]+'%22>'+%22\n%22+filter(names[l])+'		</outline>'+%22\n%22;}}else{body='		<outline%20title=%22'+names[choice]+'%22%20text=%22'+names[choice]+'%22>'+%22\n%22+filter(names[choice])+'		</outline>'+%22\n%22;}var%20tx='='+'%22';body=body.replace(/=%22\s/g,tx);body=body.replace(/&/g,'&');var%20footer='	</body>'+%22\n%22+'</opml>';var%20htmlHeader='<html><head><title>Free%20Academic%20Podcasts</title></head><body>';var%20htmlFooter='</body></html>';var%20opml=(isOPML)?header+body+footer:htmlHeader+(((((header+body+footer).replace(/&/g,'&')).replace(/>/g,'>')).replace(/</g,'<')).replace(/\n/g,'<br>\n'))+htmlFooter;function%20popOPML(code){var%20gOPML=window.open('','Free%20Academic%20Podcasts','top=300,left=200,height=480,width=640');var%20tmp=gOPML.document;tmp.open();tmp.write(code);tmp.close()}popOPML(opml);})()*/

JavaScript ID的元素

document.getElementById("invitemobile"+line).value = "";

JavaScript Capa con ancho fijo

<!--- tooltip.js -->
// position of the tooltip relative to the mouse in pixel //
var offsetx = -12;
var offsety =  8;

function newelement(newid)
{ 
    if(document.createElement)
    { 
        var el = document.createElement('div'); 
        el.id = newid;     
        with(el.style)
        { 
            display = 'none';
            position = 'absolute';
        } 
        el.innerHTML = ' '; 
        document.body.appendChild(el); 
    } 
} 
var ie5 = (document.getElementById && document.all); 
var ns6 = (document.getElementById && !document.all); 
var ua = navigator.userAgent.toLowerCase();
var isapple = (ua.indexOf('applewebkit') != -1 ? 1 : 0);
function getmouseposition(e)
{
    if(document.getElementById)
    {
        var iebody=(document.compatMode && 
        	document.compatMode != 'BackCompat') ? 
        		document.documentElement : document.body;
        pagex = (isapple == 1 ? 0:(ie5)?iebody.scrollLeft:window.pageXOffset);
        pagey = (isapple == 1 ? 0:(ie5)?iebody.scrollTop:window.pageYOffset);
        mousex = (ie5)?event.x:(ns6)?clientX = e.clientX:false;
        mousey = (ie5)?event.y:(ns6)?clientY = e.clientY:false;

        var lixlpixel_tooltip = document.getElementById('tooltip');
        lixlpixel_tooltip.style.left = (mousex+pagex+offsetx) + 'px';
        lixlpixel_tooltip.style.top = (mousey+pagey+offsety) + 'px';
    }
}
function tooltip(tip)
{
    if(!document.getElementById('tooltip')) newelement('tooltip');
    var lixlpixel_tooltip = document.getElementById('tooltip');
    lixlpixel_tooltip.innerHTML = tip;
    lixlpixel_tooltip.style.display = 'block';
    document.onmousemove = getmouseposition;
}
function exit()
{
    document.getElementById('tooltip').style.display = 'none';
}
<!-- fin tooltip.js -->

<div style="width: 52px; overflow: auto; overflow-x:hidden" onmouseover="tooltip('<%=textoCelda%>');" onmouseout="exit();" >
<%=textoCelda%>
</div>

JavaScript 修复IE中“选择下的菜单”问题

/* Son of Suckerfish Dropdowns. JS needed only for
   Internet Explorer. Documented here:
   http://www.htmldog.com/articles/suckerfish/dropdowns/*/
sfHover = function() {
    var sfEls = document.getElementById("nav").getElementsByTagName("LI");
    /* Create an array of all <select> tags on the page (could be limited to 
    those within an element with a specific id -- see line above. */
    var selects = document.getElementsByTagName("select"); 
    for (var i=0; i<sfEls.length; i++) {
        sfEls[i].onmouseover=function() {
            this.className+=" sfhover";
            for (var n=0; n<selects.length; n++) {
                /* Hides <select> tags, which appear above menu in IE */
                selects[n].className+=" hide_select";
            }
        }
        sfEls[i].onmouseout=function() {
            this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
            for (var n=0; n<selects.length; n++) {
                /* Makes <select> tags visible again */
                selects[n].className = selects[n].className.replace(new RegExp(" hide_select\\b"), "");
            }
        }
    }
}

/* 
 * NOTE: In order for this snippet to work, you need to add the 
 * following lines (or something similar) to your CSS:
 *
 * select.hide_select {
 *     visibility: hidden;
 * }
 *
 * Using "display: none" may cause other elements to shift as the is 
 * completely removed from the flow of the document. By using
 * "visibility: hidden", the just becomes "invisible."
 */