Foros del Web

Foros del Web (http://www.forosdelweb.com/)
-   Javascript (http://www.forosdelweb.com/f13/)
-   -   FAQs JavaScript (http://www.forosdelweb.com/f13/faqs-javascript-105325/)

Kaopectate 08/12/2002 21:14

51.- Frase diaria
 
P: ¿Como puedo colocar en mi página una frase distinta cada día de la semana?

R: [ver ejemplo]

Código PHP:

<html>
 <
head>
  <
script language="JavaScript">
   function 
frase(){
    var 
aFrases = new Array("Texto del Domingo"
                            
"Texto del Lunes"
                            
"Texto del Martes"
                            
"Texto del Miércoles"
                            
"Texto del Jueves"
                            
"Texto del Viernes"
                            
"Texto del Sábado");
    var 
fecha = new Date();
    var 
indice fecha.getDay();
    return 
aFrases[indice];
   }
  
</script>
 </head>
 <body>
  <form name="frm">
   <h1>
    <script language="JavaScript">
     document.write(frase());
    </script>
   </h1>
  </form>
 </body>
</html> 


Ruchu 09/12/2002 08:47

52. Un efecto chachi para texto y no muy complicado
 
un efecto chachi para texto y no muy complicado, no lo he hecho yo, lo copie de no se donde.
Código PHP:

<script>
var 
TimerID;
var 
updown true;
var 
str 1;
function 
start()
{
if (
document.all)
TimerID window.setInterval"wave()"100 );
}
function 
wave()
{
if ( 
str 10 || str )
updown = !updown;
if ( 
updown )
str++;
else
str--;
wft.filters"wave" ).phase str 20;
wft.filters"wave" ).strength str;
}
window.onload=start
</script>

<div id = "wft" style = "font-family:Arial;font-size:10pt;width:60px; filter:wave(add=0, freq=7, light=0, phase=0, strength=5)" class = "big"><b>Ruchu</b></div> 


KarlanKas 09/12/2002 15:12

53.Banners Aleatorios (GIF y SWF)
 
P: ¿Cómo puedo hacer para que cada vez que se abra una página muestre un banner aleatorio, ya sea un archivo swf o un archivo gif?
R: Este código sirve también para cualquier archivo de imagen.

Código PHP:

<html>
<
head>
    <
title>Selección de Banners Aleatorios</title>
</
head>

<
body>
<
SCRIPT LANGUAGE="JavaScript"
// Realizado por: Fabian Muller modificado por KarlanKas para forosdelweb.com 
// WebExperto.com - Ayuda al webmaster en español 
// Comienzo 

width="468"//Anchura del banner
height="60"//Altura del banner

banners= new Array();
banners[0]="banner1.gif";
banners[1]="banner2.gif";
banners[2]="banner3.swf";
banners[3]="banner4.gif";
banners[4]="banner5.swf";

totalbanners banners.length;
var 
ahora = new Date()
var 
segundos ahora.getSeconds()
var 
ad segundos totalbanners;
seleccionado=banners[ad];
localizador=seleccionado.lastIndexOf('.');
localizador2=localizador+4
extension
=seleccionado.substring(localizador+1,localizador2); 
archivo=seleccionado.substring(0,localizador);

document.write("<center>");
if (
extension=="swf"){
flash=seleccionado;
document.write('<OBJECT CLASSID=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=' width ' height=' height ' CODEBASE=\"http://active.macromedia.com/flash4/cabs/swflash.cab#version=4,0,0,0\">');
document.write('<PARAM NAME=\"MOVIE\" VALUE=\"' flash '\">');
document.write('<PARAM NAME=\"PLAY\" VALUE=\"true\">');
document.write('<PARAM NAME=\"LOOP\" VALUE=\"true\">');
document.write('<PARAM NAME=\"QUALITY\" VALUE=\"high\">');
document.write('<EMBED SRC=' flash ' width=' width ' height=' height ' PLAY=\"true\" LOOP=\"true\" QUALITY=\"high\" PLUGINSPAGE=\"http://www.macromedia.com/shockwave/download/index.cgi? P1_Prod_Version=ShockwaveFlash\">');
document.write('</EMBED>');
document.write('</OBJECT>');}
else {
document.write('<img src='+seleccionado+' width='+width+' height='+height+'>');
document.write('</center>');}
// Fin

</SCRIPT>

<!-- RESTO DE PÁGINA-->
</body>
</html> 

Espero que sirva!

CORE 09/12/2002 20:19

54 Detectar Plugins

P ¿Como detecto flash player?

R
Código PHP:

<script language="JavaScript">
<!--
function 
MM_checkPlugin(plgIntheURLaltURLautoGo) {
  var 
ok=falsedocument.MM_returnValue false;
  
with (navigator) if (appName.indexOf('Microsoft')==-|| (plugins && plugins.length)) {
    
ok=(plugins && plugins[plgIn]);
  } else if (
appVersion.indexOf('3.1')==-1) {
    if (
plgIn.indexOf("Flash")!=-&& window.MM_flash!=nullok=window.MM_flash;
    else if (
plgIn.indexOf("Director")!=-&& window.MM_dir!=nullok=window.MM_dir;
    else 
ok=autoGo; }
  if (!
oktheURL=altURL; if (theURLwindow.location=theURL;
}
//-->
</script>
</head>

<body bgcolor="#FFFFFF" text="#000000" onLoad="MM_checkPlugin('Shockwave Flash','index.html','http://www.macromedia.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash&amp;Lang=LatinAmerica&amp;P5_Language=Spanish',true);return document.MM_returnValue"> 



P¿Como detecto shockwave player?
R
Código PHP:

<script language="JavaScript">
<!--
function 
MM_checkPlugin(plgIntheURLaltURLautoGo) { //v4.0
  
var ok=falsedocument.MM_returnValue false;
  
with (navigator) if (appName.indexOf('Microsoft')==-|| (plugins && plugins.length)) {
    
ok=(plugins && plugins[plgIn]);
  } else if (
appVersion.indexOf('3.1')==-1) { //not Netscape or Win3.1
    
if (plgIn.indexOf("Flash")!=-&& window.MM_flash!=nullok=window.MM_flash;
    else if (
plgIn.indexOf("Director")!=-&& window.MM_dir!=nullok=window.MM_dir;
    else 
ok=autoGo; }
  if (!
oktheURL=altURL; if (theURLwindow.location=theURL;
}
//-->
</script>
</head>

<body bgcolor="#FFFFFF" text="#000000" onLoad="MM_checkPlugin('Shockwave for Director','index.html','http://www.macromedia.com/shockwave/download/download.cgi?Lang=LatinAmerica&amp;P5_Language=Spanish',true);return document.MM_returnValue"> 

P ¿Como detecto live audio?

R
Código PHP:

<script language="JavaScript">
<!--
function 
MM_checkPlugin(plgIntheURLaltURLautoGo) { //v4.0
  
var ok=falsedocument.MM_returnValue false;
  
with (navigator) if (appName.indexOf('Microsoft')==-|| (plugins && plugins.length)) {
    
ok=(plugins && plugins[plgIn]);
  } else if (
appVersion.indexOf('3.1')==-1) { //not Netscape or Win3.1
    
if (plgIn.indexOf("Flash")!=-&& window.MM_flash!=nullok=window.MM_flash;
    else if (
plgIn.indexOf("Director")!=-&& window.MM_dir!=nullok=window.MM_dir;
    else 
ok=autoGo; }
  if (!
oktheURL=altURL; if (theURLwindow.location=theURL;
}
//-->
</script>
</head>

<body bgcolor="#FFFFFF" text="#000000" onLoad="MM_checkPlugin('LiveAudio','index.html','http://www.live-audio.com/',true);return document.MM_returnValue"> 

P¿Como detecto Netscape Media Player?
R
Código PHP:

<script language="JavaScript">
<!--
function 
MM_checkPlugin(plgIntheURLaltURLautoGo) { //v4.0
  
var ok=falsedocument.MM_returnValue false;
  
with (navigator) if (appName.indexOf('Microsoft')==-|| (plugins && plugins.length)) {
    
ok=(plugins && plugins[plgIn]);
  } else if (
appVersion.indexOf('3.1')==-1) { //not Netscape or Win3.1
    
if (plgIn.indexOf("Flash")!=-&& window.MM_flash!=nullok=window.MM_flash;
    else if (
plgIn.indexOf("Director")!=-&& window.MM_dir!=nullok=window.MM_dir;
    else 
ok=autoGo; }
  if (!
oktheURL=altURL; if (theURLwindow.location=theURL;
}
//-->
</script>
</head>

<body bgcolor="#FFFFFF" text="#000000" onLoad="MM_checkPlugin('Netscape Media Player','index.html','http://rc.lrs.lt:8080/n/media/nmplaydn.html',true);return document.MM_returnValue"> 

P¿Como detecto quick time?
R
Código PHP:

<script language="JavaScript">
<!--
function 
MM_checkPlugin(plgIntheURLaltURLautoGo) { //v4.0
  
var ok=falsedocument.MM_returnValue false;
  
with (navigator) if (appName.indexOf('Microsoft')==-|| (plugins && plugins.length)) {
    
ok=(plugins && plugins[plgIn]);
  } else if (
appVersion.indexOf('3.1')==-1) { //not Netscape or Win3.1
    
if (plgIn.indexOf("Flash")!=-&& window.MM_flash!=nullok=window.MM_flash;
    else if (
plgIn.indexOf("Director")!=-&& window.MM_dir!=nullok=window.MM_dir;
    else 
ok=autoGo; }
  if (!
oktheURL=altURL; if (theURLwindow.location=theURL;
}
//-->
</script>
</head>

<body bgcolor="#FFFFFF" text="#000000" onLoad="MM_checkPlugin('QuickTime Plug-In','index.html','http://www.apple.com/quicktime/download/',true);return document.MM_returnValue"> 


tunait 10/12/2002 08:29

P. Cómo abrir una ventana pop-up al tamaño de una imagen?
 
R. Ver ejemplo

Código PHP:

<script language="javascript">

//script por Tunait
var ventana
var cont=0
var titulopordefecto "Perico de los palotes" //texto por defecto a mostrar en la barra de título en caso de omitir el argumento titulo

function afoto(cual,titulo)
{
if(
cont==1){ventana.close();ventana=null}
if(
titulo==null){titulo=titulopordefecto}
ventana=window.open('','ventana','resizable=yes,scrollbars=no')
ventana.document.write('<html><head><title>' titulo '</title></head><body style="overflow:hidden" marginwidth="0" marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0" scroll="no" onUnload="opener.cont=0"><img src="' cual '" onLoad="opener.redimensionar(this.width, this.height)">')
ventana.document.close()
cont++
}
function 
redimensionar(ancho,alto)
{
ventana.resizeTo(ancho+12,alto+28)
ventana.moveTo((screen.width-ancho)/2,(screen.height-alto)/2//centra la ventana. Eliminar si no se quiere centrar el popup
}
</script> 

Y luego a cada enlace a cada imagen....

desde texto: <a href="#" onClick="afoto('nombredelaimagen.jpg','Mi titulo');return false">Imagen 1 </a>

desde una imagen: <a href="#" onClick="afoto('nombredelaimagen.jpg','Mi titulo');return false"><img src="imagen.jpg"></a>

Nota: Se puede omitir el segundo argumento (titulo) al llamar a la función. En ese caso la ventana tendrá el título por defecto guardada en la variable titulopordefecto

tunait 10/12/2002 08:49

pop-up ajustada a imagen versión 2
 
R. Es una variante que incluye la posibilidad de pasar a la imagen siguiente o a la anterior desde el mismo pop-up

Código PHP:

<script language="javascript">

//Ventana ajustada a foto por tunait

var ventana
//metemos en un array el listado de las imágenes que queramos utilizar en el orden que nos interese

afotos=new Array()
afotos[0]="tibidabo.jpg"
afotos[1]="gato.jpg"
afotos[2]="paloma.jpg"
afotos[3]="perico.jpg"

function afoto(cual)
{
if(
ventana){ventana.close()}
buscar(cual)
ventana=windowopen('','ventana','resize=yes,scrollbars=no,resizable=yes')
ventana.document.write('<body marginwidth="0" marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0"><img id="foto" alt="mi foto" src="' cual '" onLoad="opener.redimensionar(this.width, this.height)">')
ventana.document.write('<br><div align="center"><a href="#" onClick="if(opener.cont==0){opener.cont=opener.afotos.length-1}else{opener.cont--};document.getElementById(\'foto\').src =opener.afotos[opener.cont];return false">anterior</a>')
ventana.document.write('  |  <a href="#" onClick="if(opener.cont==opener.afotos.length-1){opener.cont=0}else{opener.cont++};document.getElementById(\'foto\').src =opener.afotos[opener.cont];return false">siguiente</a>')
}

var 
cont
function redimensionar(anchoalto)
{
ventana.resizeTo(ancho,alto+50)
}
function 
buscar(que)
{
for(
c=0;c<afotos.length;c++)
{
   if(
afotos[c]==que)
   {
   
contc;
   return 
cont
   
break
  }
}

}
</script> 

... y luego llamamos a cada imagen a través de la función pasándole como argumento el nombre de la imagen:

<body bgcolor="#FFFFFF" text="#000000">
<div align="center"><b onClick="afoto('tibidabo.jpg')">Tibidabo</b> &nbsp;&nbsp;
<b onClick="afoto('gato.jpg')">Gato</b> &nbsp;&nbsp;<b onClick="afoto('paloma.jpg')">Paloma</b>
&nbsp;&nbsp;<b onClick="afoto('perico.jpg')">Perico</b> </div>
</body>

Carlitos 10/12/2002 12:02

57.- Mostrar/ocultar capas [Ejemplo]

P.- ¿Cómo puedo mostrar/ocultar capas pulsando sobre un enlace?

R.- Código de ejemplo. (Funciona en todos los navegadores, creo)

Código:

<html>
<head>
<script LANGUAGE="javascript">
var capa
function cambio(idCapa){
 if (document.layers) capa = eval("document." + idCapa);
 if (document.all) capa = eval(idCapa + ".style");
 if (document.getElementById) capa = eval('document.getElementById("' + idCapa + '").style');

 if ((capa.visibility == "hidden") || (capa.visibility == "hide")){
  capa.visibility = (document.layers) ? "show" : "visible" ;
 }else{
  capa.visibility = (document.layers) ? "hide" : "hidden" ;
 }
}
//-->
</script>
</head>
<body>
<div id="capa1" style='position:relative;'>
Esta es la capa 1
</div>
<div id="capa2" style='position:relative;'>
Esta es la capa 2
</div>
<a href="#" onclick="cambio('capa1')">Muestra/oculta la capa 1</a>
<br>
<a href="#" onclick="cambio('capa2')">Muestra/oculta la capa 2</a>
</body>


JavierB 10/12/2002 12:38

58.- Navegar con un menú desplegable (select)

P.- ¿Cómo puedo cambiar de página segun la opción elegida en un <select>?

R.- Con un código parecido a este:
Código PHP:

<select name="select" onChange="location.href=this.value">
  <
option value="paginauno.html">Pagina 1</option>
  <
option value="paginados.html">Pagina 1</option>
  <
option value="paginatres.html">Pagina 1</option>
</
select


Kaopectate 11/12/2002 08:19

59.- Trampa de texto
 
P: ¿Como puedo redireccionar lo escrito en un elemento HTML hacia otro elemento?

R: [ver ejemplo]

Código PHP:

<html>
 <
head>
  <
script language="JavaScript">
   function 
redirecciona(){
    if (
oTrap.checked){
     
oOutput.innerText += "[trap = " event.keyCode "]";
     
event.returnValue false;
    } else 
oOutput.innerText += String.fromCharCode(event.keyCode);
   }
  
</script>
 </head>
 <body>
  <table border="0">
   <tr>
    <td>
     Texto:<input id="oExample" type="text" onkeydown="redirecciona()">
    </td>
    <td>
     <input type="checkbox" id="oTrap"> Modo debug
    </td>
   </tr>
   <tr>
    <td colspan="2">
     <textarea id="oOutput" rows="10" cols="50"></textarea>
    </td>
   </tr>
  </table>
 </body>
</html> 


Kaopectate 11/12/2002 11:52

60.- Filtro sobre un select
 
P: ¿Como puedo filtrar los elementos que conforman un select de acuerdo a lo tipeado en un área de texto?

R: [ver ejemplo]

Código PHP:

<html>
 <
head>
  <
script language="JavaScript">

   var 
i;

   function 
addOpt(oCntrlsTxtsValsCnd){
    if (
sTxt.substr(0sCnd.length).toUpperCase() == sCnd.toUpperCase()){
     var 
selOpcion=new Option(sTxtsVal);
     eval(
oCntrl.options[i++]=selOpcion);
    }
   }

   function 
cambia(oCntrl){
    var 
txtVal document.frm.txt.value;
    while(
oCntrl.length 0oCntrl.options[0]=null;
    
0;
    
oCntrl.clear;
    
addOpt(oCntrl,  "Ciudad de México""0"txtVal);
    
addOpt(oCntrl,  "Ciudad de Panamá""0"txtVal);
    
addOpt(oCntrl,  "Ciudad de Guatemala""0"txtVal);
    
addOpt(oCntrl,  "Caracas""0"txtVal);
    
addOpt(oCntrl,  "Cancún""0"txtVal);
    
addOpt(oCntrl,  "Maracay""0"txtVal);
    
addOpt(oCntrl,  "Maracaibo""0"txtVal);
    
addOpt(oCntrl,  "Zaragoza""0"txtVal);
   }
  
</script>
 </head>
 <body onload="cambia(document.frm.ciudad)">
  <form name="frm">
   <table border="0">
    <tr>
     <td>
      Ciudad:
     </td>
     <td>
      <input type="text" name="txt" onkeyup="cambia(document.frm.ciudad)">
     </td>
     <td>
      <select name="ciudad">
      </select>
     </td>
    </tr>
   </table>
  </form>
 </body>
</html> 


Carlitos 11/12/2002 11:55

61.- Onload [Ejemplo]

P.- ¿Cómo ejecutar un script al entrar en una página?

R.- Añadiendo el evento onLoad a la etiqueta <body>

Ejemplo:

Código:

<head>
<script>
function entrada()
{
alert("Hola!!")
}
</script>
</head>
<body onLoad="entrada()">
...
...
</body>


Carlitos 11/12/2002 11:58

62.- Onunload [Ejemplo]

P.- ¿Cómo ejecutar un script al salir de una página?

R.- Añadiendo el evento onUnload a la etiqueta <body>

Ejemplo:

Código:

<head>
<script>
function salida()
{
alert("Adios!!")
}
</script>
</head>
<body onUnload="salida()">
...
...
</body>


Carlitos 11/12/2002 12:23

63.- Detectar tecla [Ejemplo]

P.- ¿Como puedo detectar la tecla pulsada?

R.- Código de ejemplo:

Código:

<html>
<script>
function mostrar(caracter) {
esNetscape=(document.layers);
letra = (esNetscape) ? caracter.which : event.keyCode;
l = String.fromCharCode(letra)
alert("Usted presionó la letra: "+l+" Codigo: "+letra)
}
document.onkeypress = mostrar;
</script>
<body>
Pulsa una tecla.
</body>
</html>


Kaopectate 11/12/2002 12:44

64.- Llenar una lista en base a otra lista
 
P: ¿Como puedo hacer una interfase con la que pueda llenar una lista en base a los elementos de otra lista?

R: [ver ejemplo]

Código PHP:

<html>
 <
head>
  <
script language="javascript">
   var 
aList = new Array("uno""dos""tres""cuatro""cinco""seis""siete""ocho""nueve""diez");
   var 
aIzqu = new Array(truetruetruetruetruetruetruetruetruetrue);
   var 
ijnIzqnDermaxIzqmaxDer;

   
nIzq 0;
   
nDer 0;
   
maxIzq aList.length;
   
maxDer 0;

   function 
agregaTodos(){
    for (
0aList.lengthi++)
      
aIzqu[i] = false;
    
maxIzq 0;
    
maxDer aList.length;
    
nIzq 0;
    
formulario();
   }

   function 
indiceIzqReal(nInd){
    var 
bFin false;
    var 
0;
    var 
= -1;
    for (;!
bFin;){
     if (
aIzqu[i]) j++;
     
bFin = ((== nInd) || (>= aList.length));
     if (!
bFini++;
    }
    return 
i;
   }

   function 
indiceDerReal(nInd){
    var 
bFin false;
    var 
0;
    var 
= -1;
    for (;!
bFin;){
     if (!
aIzqu[i]) j++;
     
bFin = ((== nInd) || (>= aList.length));
     if (!
bFini++;
    }
    return 
i;
   }

   function 
agregaActual(){
    var 
bFin false;
    var 
nInd indiceIzqReal(nIzq);
    
aIzqu[nInd] = false;
    if (
nIzq == maxIzq 1nIzq--;
    
maxIzq--;
    
maxDer++;
    
formulario();
   }

   function 
eliminaActual(){
    var 
bFin false;
    var 
nInd indiceDerReal(nDer);
    
aIzqu[nInd] = true;
    if (
nDer == maxDer 1nDer--;
    
maxIzq++;
    
maxDer--;
    
formulario();
   }

   function 
eliminaTodos(){
    for (
0aList.lengthi++)
      
aIzqu[i] = true;
    
maxIzq aList.length;
    
maxDer 0;
    
nDer 0;
    
formulario();
   }

   function 
primeroIzq(){
    
nIzq 0;
    
formulario();
   }

   function 
primeroDer(){
    
nDer 0;
    
formulario();
   }

   function 
siguienteIzq(){
    if (
nIzq maxIzq 1)
     
nIzq++;
    
formulario();
   }

   function 
siguienteDer(){
    if (
nDer maxDer 1)
     
nDer++;
    
formulario();
   }

   function 
anteriorIzq(){
    if (
nIzq 0)
     
nIzq--;
    
formulario();
   }

   function 
anteriorDer(){
    if (
nDer 0)
     
nDer--;
    
formulario();
   }

   function 
ultimoIzq(){
    
nIzq maxIzq 1;
    
formulario();
   }

   function 
ultimoDer(){
    
nDer maxDer 1;
    
formulario();
   }

   function 
formulario(){
    
with (window.pantalla.document){
     
open();
     
writeln("<html>");
     
writeln(" <head>");
     
writeln(" </head>");
     
writeln(" <body>");
     
writeln("  <form name='formulario'>");
     
writeln("   <table border='0'>");
     
writeln("    <tr>");
     
writeln("     <td>");
     
writeln("      <textarea name='opciones' rows='10'>");
     for (
00aList.lengthi++){
      if (
aIzqu[i]){
       if (
== nIzq)
        
writeln('>>' aList[i] + '<<')
       else
        
writeln(aList[i]);
       
j++;
      }
     }
     
writeln("      </textarea>");
     
writeln("     </td>");
     
writeln("     <td>");
     
writeln("      <table border='0'>");
     
writeln("       <tr>");
     
writeln("        <td>");
     
writeln("         <input type='button' value='>>' onclick='parent.agregaTodos()'>");

     
writeln("        </td>");
     
writeln("       </tr>");
     
writeln("       <tr>");
     
writeln("        <td>");
     
writeln("         <input type='button' value='> ' onclick='parent.agregaActual()'>");

     
writeln("        </td>");
     
writeln("       </tr>");
     
writeln("       <tr>");
     
writeln("        <td>");
     
writeln("         <input type='button' value=' <' onclick='parent.eliminaActual()'>");

     
writeln("        </td>");
     
writeln("       </tr>");
     
writeln("       <tr>");
     
writeln("        <td>");
     
writeln("         <input type='button' value='<<' onclick='parent.eliminaTodos()'>");

     
writeln("        </td>");
     
writeln("       </tr>");
     
writeln("      </table>");
     
writeln("     </td>");
     
writeln("     <td>");

     
writeln("      <textarea name='seleccionados' rows='10'>");
     for (
00aList.lengthi++){
      if (!
aIzqu[i]){
       if (
== nDer)
        
writeln('>>' aList[i] + '<<')
       else
        
writeln(aList[i]);
       
j++;
      }
     }
     
writeln("      </textarea>");

     
writeln("     </td>");
     
writeln("    </tr>");
     
writeln("    <tr>");
     
writeln("    </tr>");
     
writeln("     <td>");
     
writeln("      <table border='0'>");
     
writeln("       <tr>");
     
writeln("        <td>");
     
writeln("         <input type='button' value='Pri' onclick='parent.primeroIzq()'>");
     
writeln("        </td>");
     
writeln("        <td>");
     
writeln("         <input type='button' value='Ant' onclick='parent.anteriorIzq()'>");
     
writeln("        </td>");
     
writeln("        <td>");
     
writeln("         <input type='button' value='Sig' onclick='parent.siguienteIzq()'>");
     
writeln("        </td>");
     
writeln("        <td>");
     
writeln("         <input type='button' value='Ult' onclick='parent.ultimoIzq()'>");
     
writeln("        </td>");
     
writeln("       </tr>");
     
writeln("      </table>");
     
writeln("     </td>");
     
writeln("     <td>");
     
writeln("     </td>");
     
writeln("     <td>");
     
writeln("      <table border='0'>");
     
writeln("       <tr>");
     
writeln("        <td>");
     
writeln("         <input type='button' value='Pri' onclick='parent.primeroDer()'>");
     
writeln("        </td>");
     
writeln("        <td>");
     
writeln("         <input type='button' value='Ant' onclick='parent.anteriorDer()'>");
     
writeln("        </td>");
     
writeln("        <td>");
     
writeln("         <input type='button' value='Sig' onclick='parent.siguienteDer()'>");
     
writeln("        </td>");
     
writeln("        <td>");
     
writeln("         <input type='button' value='Ult' onclick='parent.ultimoDer()'>");
     
writeln("        </td>");
     
writeln("       </tr>");
     
writeln("      </table>");
     
writeln("     </td>");
     
writeln("   </table>");
     
writeln(" </form>");
     
writeln("</body>");
     
writeln("</html>");
     
close();
    }
   }

  
</script>

 </head>
 <frameset rows="100%,*" frameborder="no" border="0" framespacing="0" onload="javascript:formulario()">
  <frame name="pantalla" src="pruDummy.htm" frameborder="no" border="0">
  <frame name="dummy" src="pruDummy.htm">
 </frameset>
</html> 


JavierB 11/12/2002 14:13

65.- Abrir un Pop-up centrado en la pantalla
 
P.- ¿Como puedo abrir un Pop-up y que quede centrado en la pantalla en cualquier resolución?

R.- Haciendo el Pop-up parecido a esto:
Código PHP:

<html>
<
head>
<
script>
function 
centrar() {
    
iz=(screen.width-document.body.clientWidth) / 2;
    
de=(screen.height-document.body.clientHeight) / 2;
    
moveTo(iz,de);
}    
</script>
</head>
<body bgcolor="#FFFFFF" text="#000000" onload="centrar()">
Segunda página
</body>
</html> 


Kaopectate 13/12/2002 14:58

66.- Login
 
P: ¿Cual es el esquema usado para identificar un usuario registrado en una página?

R: [ver ejemplo]

Aunque la identificación de un usuario es un problema que debe atenderse en el lado del servidor usando PHP o ASP o JSP, hay también una porción del código que debe hacerse del lado del cliente usando JavaScript.

El siguiente esquema es una "simulación" del proceso de validación, que pasa como parámetro el nombre del usuario. En una solución real, dicho usuario debe ser registrado en una variable del lado del servidor o una cookie.

Login0.htm
Código PHP:

<html>
 <
head>
  <
script language="JavaScript">

   var 
usuario "";

   function 
valParam(urlprmName){ 
    var 
prmUpper prmName.toUpperCase();
    var 
prmPosic url.indexOf(prmUpper);
    var 
sepPos;
    if (
prmPosic != -1){
     var 
sepPos url.indexOf("&"prmPosic);
     if (
sepPos != -1){
      return 
url.substring(prmPosic prmUpper.length 1sepPos);
     } else {
      return 
url.substring(prmPosic prmUpper.length 1url.length);
     }
    } else {
     return 
"";
    }
   }

   function 
getParameters(){
    var 
remplaza = /+/gi
    var 
url window.location.href;
    var 
variable;
    
url unescape(url);
    
url url.replace(remplaza" ");
    
url url.toUpperCase();
    
usuario valParam(url"Usr");
   }

   function 
popup(){
    
open("login1.htm");
   }

   function 
salir(){
    
location.href "login0.htm?Usr=.";
   }
  
</script>
 </head>
 <body>
  <form name="frm">
   <table border="0" width="100%">
    <tr>
     <td width="100%" align="right">
      <script language="JavaScript">
       getParameters();
       if (usuario == "" || usuario == "."){
        document.write("<a href='#' onclick='popup()'>Conectarse</a>");
       } else {
        document.write("Hola " + usuario + "&nbsp;");
        document.write("<a href='login0.htm?Usr='>Desconectarse</a>");
       }
      </script>
     </td>
    </tr>
   </table>
  </form>
 </body>
</html> 

Login1.htm
Código PHP:

<html>
 <
head>
  <
script language="JavaScript">
   function 
reposiciona(){
    var 
ancho screen.width;
    var 
alto  screen.height;
    
resizeTo(300250);
    
moveTo((ancho 300) / 2, (alto 250) / 2);
   }

   function 
entrar(){
    
opener.location.href "login0.htm?Usr=" document.form2.nomb.value;
    
close();
   }
  
</script>
 </head>
 <body onload="reposiciona()">
  <form name="form2">
   <table border="0">
    <tr>
     <td align="right">
      Nombre:
     </td>
     <td>
      <input type="text" name="nomb"><br>
     </td>
    </tr>
    <tr>
     <td align="right">
      Clave:
     </td>
     <td>
      <input type="password" name="key"><br>
     </td>
    </tr>
    <tr>
     <td align="center" colspan="2">
      <input type="button" value="Login" onclick="entrar()">
     </td>
    </tr>
  </form>
 </body>
</html> 


Carlitos 13/12/2002 15:53

67.- Precarga

P.- ¿Cómo realizo una precarga de imágenes?

R.- Colocando esto en el head

Código:

<script>
var foto=new Array()
foto[0]=new Image()
foto[0].src="pepito.jpg"
foto[1]=new Image()
foto[1].src="jaimito.jpg"
foto[2]=new Image()
foto[2].src="jorgito.jpg"
</script>

En este ejemplo, se precargan tres imágenes. La forma de llamar a esas imagenes, es la habitual:

Código:

<img src="pepito.jpg">

Carlitos 13/12/2002 16:21

68.- Rollover [Ejemplo]

P.- ¿Cómo cambio una imagen por otra al pasar por encima con el puntero del ratón?

R.- Podemos usar esto, por ejemplo para cambiar la apariencia de un boton. (Normal, sobre y pulsado)

Esto en el head
Código:

<script>
var foto=new Array()
foto[0]=new Image()
foto[0].src="boton.gif"
foto[1]=new Image()
foto[1].src="boton_sobre.gif"
foto[2]=new Image()
foto[2].src="boton_pulsado.gif"
</script>

Esto en el body
Código:

<img src="boton.gif" onmouseover="this.src=foto[1].src" onmouseout="this.src=foto[2].src" onclick="this.src=foto[0].src">
onmouseover = encima
onmouseout = fuera
onmousedown = click

Kaopectate 13/12/2002 17:14

69.- Manuales, Tutoriales y Cursos electrónicos de JavaScript
 
P: ¿Donde puedo conseguir manuales, tutoriales, cursos o información técnica de JavaScript?

R:

Algunos sitios en español:

1.- Curso en WebMonkey
2.- Tutorial en Wanadoo
3.- Manual en webEstilo
4.- Tutorial en Lovecraft
5.- ElGuruProgramador
6.- Un tutorial de Productos QRT
7.- Tutorial en TeleProgramadores
8.- Tutorial en Programacion.com
9.- Manual en DesarrolloWeb
10.- Tutorial en El rincón del programador
11.- JavaScript desde cero en Ciudad Futura
12.- Curso en Programacion.com
13.- Manual en 148.216.5.25
14.- Tutorial en Orbita
15.- Tutorial de la Universidad de Málaga
16.- Tutorial en LoboWeb_2
17.- Manual en AUI
18.- Introducción al JavaScript por Stefan Koch
19.- Archivo zip descargable desde servidor gratuito


Sitios en inglés:

1.- Documentación oficial de Netscape
2.- Documentación de JScript de Microsoft
3.- Estandard ECMA-262
4.- Propuesta Netscape para un ECMAScript 4
5.- Propuesta de JavaScript 2.0
6.- Reporte Técnico DOM (Document Object Model)
7.- DOM en Mozilla
8.- Referencia JavaScript en NetScape
9.- Referencia JavaScript en MSDN
10.- Diferencias en Opera 6 respecto al estandard DOM
11.- Especificaciones soportadas por Opera 7

(Si deseas añadir una dirección distinta a las anteriores, hazlo aqui y será agregada a la lista lo antes posible).

Kaopectate 16/12/2002 11:49

70.- Código JavaScript en la red
 
P: ¿Donde puedo conseguir código JavaScript?

R:

He aqui algunas direcciones:

1.- Softonic.com
2.- Elosan
3.- WebTutorial.com.ar
4.- DynamicDrive.com
5.- MundoJavaScript.com
6.- HotScripts.com
7.- JavaScript.com
8.- javascript.internet.com
9.- DHTMLShock.com
10.- webdeveloper.earthweb.com
11.- javascriptkit.com
12.- jsmadeeasy.com
13.- dithered.com
14.- scriptsearch.com
15.- LoneWolf's Domain
16.- dhtmlcentral.com
17.- Kurt's HTML
18.- miscodigos.com
19.- tecnocodigo.com
20.- JavaBoutique.internet.com
21.- JavaScript Examples.com
22.- construyetuweb.netfirms.com
23.- htmlpoint.com
24.- Mi reportaje.com

Servicios específicos:

1.- Editor HTML en interactivetools.com

(Si deseas añadir una dirección distinta a las anteriores, hazlo aqui y será agregada a la lista lo antes
posible).

chivi 16/12/2002 16:47

71.- Sonido en los Enlaces
 
Pregunta:
¿Cómo puedo poner un sonido a mis enlaces al situar el ratón encima?

Respuesta:
Código PHP:

<html>
<
head>
<
script>
function 
Reproducir(){
document.all.sound.src "archivo.wav"}
function 
Parar(){
document.all.sound.src ""}
</script>
</head>
<body>
En el Body:
<bgsound id="sound">
<a href="pagina_que_sea" onmouseover="Reproducir()" onmouseout="Parar()">Enlace 1</a>
<a href="pagina_que_sea" onmouseover="Reproducir()" onmouseout="Parar()">Enlace 2</a>
</body>
</html> 


KarlanKas 17/12/2002 09:15

72. Conocer los entresijos del navegador
 
P: ¿Cómo conocer los detalles del visitante de mi página?
R: Preguntándoselos o con ste código:

Código PHP:

<html>
<
head>
</
head>

<
body style="font:normal 10px/20px verdana;">
<
script>
document.write("<b>Motor del Navegador:</b> "+navigator.appCodeName+"<br>");
document.write("<b>El Navegador es: </b>"+navigator.appName+"<br>");
document.write("<b>LA versión del Navegador es:</b> "+navigator.appVersion+"<br>");
if (
navigator.javaEnabled())document.write("Tiene Java activado<br>");
else 
document.write("No tiene Java activado <br>");
document.write("<b>Motor del Navegador:</b> "+navigator.userAgent+"<br>");
document.write("<b>Idioma del Navegador:</b> "+navigator.userLanguage+"<br>");
document.write("<b>Anchura de la Pantalla:</b>"+screen.width+" pixels<br>");
document.write("<b>Altura de la Pantalla:</b>"+screen.height+" pixels<br>");

</script>
</body>
</html> 

Salu2

Kaopectate 17/12/2002 12:10

73.- Desactivar la tecla F5
 
P: ¿Como puedo evitar que el usuario refresque la página usando la tecla F5?

Créditos: Yanix

R: [ver ejemplo]

Código PHP:

<html>
 <
head>
  <
script language="javascript">

   
document.onkeydown = function(){ 
    if(
window.event && window.event.keyCode == 116){
     
window.event.keyCode 505
    }
    if(
window.event && window.event.keyCode == 505){ 
     return 
false;    
    } 
   } 

   function 
pon_hora(){
    var 
dHora = new Date();
    var 
res String(dHora.getHours()) + ":" String(dHora.getMinutes()) + ":" String(dHora.getSeconds());
    
document.frm.txt.value res;
    return 
res;
   }

  
</script> 
 </head>
 <body onload="pon_hora()">
  <form name="frm">
   <h1><b>ANULACIÓN DE LA TECLA TECLA F5</b><br></h1>
   Hora actual:&nbsp;<input type="text" name="txt"><br><br>
   (Al seleccionar el botón "Actualizar" del navegador la hora debería actualizarse, pero con la tecla F5 no)
  </form>
 </body>
</html> 


Kaopectate 17/12/2002 20:41

74.- Libros sobre JavaScript
 
P: ¿Quien me puede recomendar un buen libro de JavaScript?

R:

He aqui algunos:

Título: JavaScript Programmer's Reference
Autor: Cliff Wooton
Editorial: Wrox
Idioma: Inglés (y del duro)
Comentarios: Exelente manual de referencia. Incluye compatibilidad de cada elemento hasta IE-5, NS-6, O-6. Incluye CD. (Kaopectate)

Título: Programación en JavaScript
Autor: Danny Goomand
Editorial: Anaya (série VIA@Internet)
Idioma: Español
Comentarios: No está mal para aprender .. es muy básico pero más o menos trata un amplio abanico del tema javascript en 534 páginas ..(Cluster)

Título: JavaScript: The Definitive Guide
Autor: David Flanagan
Editorial: O'Reilly
Idioma: Inglés
Comentarios:

Título: JavaScript: A Beginner's Guide
Autor: John Pollock
Editorial: Osborne Mc Graw Hill
Idioma: Inglés
Comentarios:

Título: JavaScript Bible, 4th Edition
Autor: Danny Goodman, Brendan Eich
Editorial: Wiley Bibles
Idioma: Inglés
Comentarios:

Título: Javascript. Tercera edición
Autor: Negrino, T. y Smith, D.
Editorial: Prentice Hall
Idioma: Español
Comentarios: Este libro me gusta mucho. Es eminentemente práctico. Todo lo enseña con ejemplos. Te puedes descargar los ejemplos de internet. La traducción es muy buena. Además hace distinciones entre NS e IE. Tal vez esté un poco desfasado ya ue esta hecho para las versiones 4.0 de los navegadores. (Aunque eso tal vez sea una ventaja de cara a buscar la compatibilidad). La verdad es que lo uso como libro de referencia... Aunque a veces para entretenerme lo leo ientras desayuno un domingo. Los ejemplos son realmente interesantes. (KarlanKas)

Título: DHTML HTML Dinámico
Autor: Gulbransen, D
Editorial: Prentice Hall
Idioma: Español
Comentarios: Este libro es bastante más completo que el anterior. Hace referencia a CSS y las relaciona con JS. Habla principalmente de IE y la traducción a veces falla un poco. El glosario del final del liro es realmente malo. Tiene un espiritu didáctico muy bueno. se hace sencilla su lectura. No sé si venía con un CD.. y si venía lo he perdido Ahora que lo pienso creo que no. Este como libro de referencia también es muy útil!. (KarlanKas)

Título: Diseño de páginas interactivas con JavaScript
Autor: Juan Carlos Orós
Editorial: Ra-Ma
Idioma: Español
Comentarios: Para empezar y como libro de apoyo, está bien. Contiene un capítulo sobre las hojas de estilo. El índice alfabético no es de los mejores. Incluye disco de 3"1/2 con ejemplos. (Carlitos)

(Si deseas añadir la decripción de otro libro, hazlo aqui y será agregada a la lista lo antes
posible).

Kaopectate 18/12/2002 10:38

75.- Saltos dentro de la página
 
P: ¿Como puedo mediante un botón, un link o una letra presionada en un área de texto, hacer un salto a una etiqueta interna dentro de mi página?

R: [ver ejemplo]

Código PHP:

<html>
 <
head>
  <
script language="JavaScript">

   function 
salta(sChar){
    
location.href "#" sChar;
   }

   function 
procesa(){
    if(
window.event.keyCode == 65salta("a");
    if(
window.event.keyCode == 66salta("b");
    if(
window.event.keyCode == 67salta("c");
    if(
window.event.keyCode == 68salta("d");
    if(
window.event.keyCode == 69salta("e");
   }

  
</script>
 </head>
 <body>
  <form name="frm">
   <table border="0">
    <tr>
     <td>
      <a href="#a">A</a>
      <a href="#b">B</a>
      <a href="#c">C</a>
      <a href="#d">D</a>
      <a href="#e">E</a>
     </td>
     <td>
      <input type="button" value="A" onclick="salta('a')">
      <input type="button" value="B" onclick="salta('b')">
      <input type="button" value="C" onclick="salta('c')">
      <input type="button" value="D" onclick="salta('d')">
      <input type="button" value="E" onclick="salta('e')">
     </td>
     <td>
      <input type="text" onKeyUp="procesa()">
     </td>
    </tr>
   </table>
   <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
   <a name="a"></a>Letra A:
   <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
   <a name="b">Letra B:
   <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
   <a name="c">Letra C:
   <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
   <a name="d">Letra D:
   <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
   <a name="e">Letra E:
  </form>
 </body>
</html> 


chivi 19/12/2002 11:55

76.- Abirir Pop-Up en Correo Web
 
Pregunta:
¿Cómo puedo abirir un Pop-Up en un Correo Web, tras pulsar en un enlace?

Respuesta:
Código PHP:

<html>
<
head>
<
script language="JavaScript">
function 
Ventana(){
windowopen('pagina','frame','toolbar=no,directories=no,menubar=no,status=no,height=300,width=300');}
</script>
</head>
<body>
<object id="Cerrar" type="application/x-oleobject" 
  classid="clsid:adb880a6-d8ff-11cf-9377-00aa003b7a11"
  codebase="http://activex.microsoft.com/activex/controls/htmlhelp/HHCTRL.ocx#Version=4,72,8252,0"
  width=0 height=0>
<param name="Command" value="Close">
</object>
<body onLoad="Cerrar.Click(); Ventana();">
</body>
</html> 

Ese código debe estar en la página a llamar desde el Correo Web.

KarlanKas 20/12/2002 09:18

77.Redirección a página alternativa
 
P.- ¿Cómo hacer que un enlace apunte a una página alternativa si la primera está caida?

R.- Con este código: Ver Ejemplo
Código PHP:

<html>
<
head>
    <
title>Redirección selectiva</title>
<
style>
#enlace{
cursor:hand;
}
</
style>
<
script>

//Script original de KarlanKas para forosdelweb.com

var imagenPrimera=new Image;
var 
imagenSegunda=new Image;

imagenPrimera.src="http://80.24.56.172/karlankas.jpg"//La imagen primera tiene que estar en el servidor donde esté direcciónPrimera
imagenSegunda.src="http://www.arquo.com/Imagenes/logotipo.jpg";

direccionPrimera="http://80.24.56.172";
direccionSegunda="http://www.arquo.com";


direccion=direccionPrimera;

function 
unError(imag){
imag.src=imagenSegunda.src;
direccion=direccionSegunda
}
</script>
</head>
<body>
<center>
<div id="cuerpo"></div>
<script>

codigo="<img id='enlace' src='"+imagenPrimera.src+"' onError='unError(this)'    onClick='location.replace(direccion);'>"
cuerpo.innerHTML=codigo
</script>
<br>
</center>
</body>
</html> 


tunait 20/12/2002 14:03

78. Cambio de Imágenes automático
 
P.- ¿Cómo puedo hacer una secuencia de imágenes que cambien de forma automática?

R.- NOTA: El efecto de la transición sólo es visible en IExplorer
NOTA2: Es recomendado que las imágenes tengan todas el mismo tamaño para lograr un mejor efecto en la transición.

Código PHP:

<script language="javascript">

//Aquí cambia los nombres de las imágenes por las tuyas.
var imagenes=new Array()

imagenes[0]=new Image (380,288);
imagenes[0].src="tibidabo.jpg"
imagenes[1]=new Image (399,291);
imagenes[1].src="gato.jpg"
imagenes[2]=new Image (248,289);
imagenes[2].src="paloma.jpg"
imagenes[3]=new Image (215,366);
imagenes[3].src="perico.jpg"

cont=0
function presImagen()
{
if (
document.all){
document.getElementById('foto').filters.blendTrans.apply()
document.getElementById('foto').src=imagenes[cont].src
document
.getElementById('foto').filters.blendTrans.play()
}
else
    {
    
document.images.foto.src imagenes[cont].src
    
}
if (
cont imagenes.length-1)
{
cont ++}
else
{
cont=0}
tiempo=window.setTimeout('presImagen()',5000)
 
//cada 5000 milisegundos (5 seg.) cambia la imagen.
//cambia la cantidad por el tiempo que quieras que transcurra entre imagen e imagen
}

</script>
</head>

<body bgcolor="#FFFFFF" text="#000000" onLoad="presImagen()">
<img id="foto" src="tibidabo.jpg" style="filter:blendTrans(duration=[B]3[/B])">
<!-- la duración de la transición es de 3 segundos. 
Cambia este valor según tus preferencias -->
</body> 

Ver Ejemplo

KarlanKas 21/12/2002 10:27

79. Mostrar teclado en pantalla
 
P.- Me gustaría que huiese un pequeño teclado en mi página web, ¿Cómo lo hago?
R.- Con este código http://eur.i1.yimg.com/eur.yimg.com/i/es/g/nuevo.gif ¡¡ahora con tecla de borrar, mayusculas/minúsculas y teclado QWERTY!! Ahora compatible con firefox:Ver Ejemplo
Código PHP:

<html>
<
head>
<
title>79.-Teclado</title>
<
script>
//Script absurdo y original de KarlanKas para forosdelweb.com

texto="";
var 
Tletras=new Array ("Q","W","E","R","T","Y","U","I","O","P","A","S","D","F","G","H","J","K","L","Ñ","Z","X","C","V","B","N","M",",",".");
var 
z=0;
var 
mayus=true
function anadir(letra){

texto=document.getElementById("barra").value;
if(
letra=="<<"){
numeroLetras=texto.length-1
texto
=texto.substring(0,numeroLetras);
}
else{
if(!
mayus){letra=letra.toLowerCase()}
texto=texto+letra;
}
document.getElementById("barra").value=texto;
}
function 
mostrar(){
if (
z==0){z=1;document.getElementById("botones").style.display="block";pregunta.innerText="Ocultar teclado";}
else {
z=0;document.getElementById("botones").style.display="none";pregunta.innerText="Mostrar teclado";}
 }
 function 
cambiomayus(aqui){
 if(
aqui.checked){mayus=true}
 else{
mayus=false}
 }
 
</script>
   
</head>

<body style="font:normal 10px/15px verdana">
<center>
<div style="width:300px">
<input type="Text" id="barra" name="barra" style="width:300px;border:solid 1px black" ><br>
<br>
<div align=center id="botones" style="font:normal 8px/4px verdana;display:none;"></div>
<script>
var letras="";
var p=0;
for (a=0;a<Tletras.length;a++){
letras=letras+"<input style='width:20px;' type='Button' value="+Tletras[a]+" onclick=anadir('"+Tletras[a]+"')>&nbsp;";
p=p+1;
if(p==10){p=0;letras=letras+"<br><br>";}
}
botones.innerHTML=letras+"<input style='width:20px;' alt='Borrar' type='Button' value=&laquo; onClick=anadir('<<')><br><br><input style='width:205px;height:22px;' type='Button' value='espacio' onclick=anadir('&#160')><br><input type=checkbox name=mayusculas onclick='cambiomayus(this)' checked><font style='font:10px'>Mayusculas</font>";

</script>
<a id="pregunta" href=javascript:mostrar()>Mostrar teclado</a><br>
</div>
</center>
</body>
</html> 


tunait 23/12/2002 12:53

80.-Redireccionar una página a su estructura de marcos cargando por defecto dicha pág
 
P.- ¿Cómo puedo lograr que si alguien llega a una sección de mi sitio sin cargar los frames, ésta se redirija a la estructura de marcos cargando por defecto dicha sección?

R.-

Habrá que crear la estructura de frames de forma dinámica mediante document.write.
Este ejemplo es para una estructura de 2 frames.
Si se quieren más frames es sólo cuestión de pedir al script que te los escriba de la misma forma que el resto.

Página de frames frames.htm
Código PHP:

<html>
<
head>
<
title>Página de Marcos</title>
<
script language="javascript">
//###script por tunait

cadena=document.location.search.substring(1,location.search.length);
cadena2=cadena.split('=')
pagina=cadena2[1]
if (
pagina==null)
  {
  
pagina='principal.htm'
  
}
document.write('<frameset rows="80,*" frameborder="YES" border="1" framespacing="1" cols="*">')
document.write(' <frame name="arriba" scrolling="NO" noresize src="arriba.htm" >')
document.write('<frame name="principal" src="' pagina '">')
document.write ('</frameset>')
</script>
</head>
<noframes> 
<body bgcolor="#FFFFFF" text="#000000">
</body>
</noframes> 
</html> 

...y el siguiente código habrá que añadirlo en algún lugar entre los tags <head> y </head> a todas las páginas (secciones) que hayan de cargarse dentro del frame principal:

Código PHP:

<script language="javascript">
url=this.location.pathname
if(top==selftop.location="frames.htm?url=" url
</script>
 

Es recomendado además añadir a las páginas que se hayan de cargar en el otro u otros marcos que no sean el principal el código que es encuentra en estas mismas FAQ's 44.- Frames

epa2 27/12/2002 02:54

81.- Apertura lateral de una ventana
 
P: ¿Como puedo abrir una ventana de izquierda a derecha?

R: Abre Una Ventana Lateralmente De Izquierda A Derecha Dando Un Muy Buen Efecto.

[ver ejemplo]


Si Deseas Que La Ventana Tenga Una Anchura Y Algura Especifica Reemplaza:

"screen.height" (alto)
"screen.width" (ancho)

Por Los Valores Deseados, Tambien Puedes Modificar moveTo(0,0) Para Acomodar La Ventana En Una Determinada Posicion X,Y De La Pantalla.

Código:

<script languaje="JavaScript">
ventana=window.open("","","width=100,height=screen.height")
ventana.moveTo(0,0)
a=100
for (a; a<screen.width; a+=10)
{
  ventana.resizeBy(10,0)
}
</script>

NOTA: acuerdate que esto va en el tag HEAD y que luego en el body tienes que hacer la llamada para abrir la ventana.(creo yo :pensando: ) .Espero que mi profe de javascript se sienta orgulloso algún dia de su torpe alumno. :-(
Adiós

CHuLoSoY 29/12/2002 16:15

82.- Deshabilitar selección de texto
 
P: Como deshabilito la selección de un texto?

r:Aunque es imposible bloquear el copiado de cualquier elemento de la página vamos a ponérselo unpoco más difícil a los copiones y vamos a deshabilitar la opción de marcar o seleccionar un texto:

Código PHP:

<script language="JavaScript">
function 
disableselect(e)
{
   return 
false
}
function 
reEnable()
{
   return 
true
}
//if IE4+
document.onselectstart=new Function ("return false")
//if NS6
if (window.sidebar)
{
   
document.onmousedown=disableselect
   document
.onclick=reEnable
}
</script> 

NOTA: Sacado de www.mundomikeoldfield.es.vg , no sé el nombre ni email del autor original, sino lo ponía. Este script circula por todo internet sin el copyright, por eso me es imposible saberlo. Perdón si se ofende alguien.

epa2 30/12/2002 06:51

83.-Dar estilos CSS para los links

P: ¿como doy estilos CSS a los hipervinculos?

[R:]Bueno, es un sistema sencillo para darle un toque de alegría a nuestras páginas. me lo bajé de la página de bravenet. si me equivoco y lo publico en el de javascript en vez de en el de HTML, pido disculpas, pero tiene algo de javascript :pensando: [/b]

CAMBIA COLOR AL PASAR EL RATÓN POR LO ALTO DEL ENLACE...

<a href="" onmouseover="this.style.color='red';" onmouseout="this.style.color='';">This HREF turns red on hover.</a>

----------------------------------------------------------------
HIPERVINCULOS O LINKS DE COLOR VERDE.

<a href="" style="color:green;">This HREF is green.</a>


-----------------------------------------------------------------------
HIPERVINCULO SIN RAYA POR DEBAJO

<a href="" style="text-decoration: none;">This HREF has no underline.</a>

---------------------------------------------------------------------
LINEA DE ESPACIO DE UN HIPERVINCULO

<a href="" style="line-spacing:150%;">These HREFs are spaced 150% of normal.</a>
<a href="" style="line-spacing:150%;">These HREFs are spaced 150% of normal.</a>

-----------------------------------------------------------------------

ESPACIO ENTRE LOS CARACTERES DE UN HIPERVINCULO

<a href="" style="letter-spacing:5px;">This HREF has 5 pixels between letters</a>
-----------------------------------------------------------------------

COLOR DE FONDO EN LOS LINKS

<a href="" style="background:ffffcc;">This HREF has a yellow background.</a>
-----------------------------------------------------------------------

podeis ver el ejemplo furulando aqui

Yanix 30/12/2002 07:44

84. Crear botón de "guardar como"
 
P . ¿Cómo crear botón de "guardar como..."?

R.

Código:

<HTML>
<HEAD>
<script language="javascript">
function guardarcomo()
{
var WebBrowser = '<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>';
document.body.insertAdjacentHTML('beforeEnd', WebBrowser);
WebBrowser1.ExecWB(4, 0);
WebBrowser1.outerHTML = "";
}
</script>
</HEAD>
<BODY>
Oprime el botón para guardar esta página...<BR>
<input type="submit" value="  Guardar  " onClick=guardarcomo() name="miboton">
</BODY>
</HTML>

Sirve para IE 5.5+
No sé si versiones anteriores.

SpiceMan 30/12/2002 21:03

85. Cómo validar una dirección de email utilizando expresiones regulares
 
P: ¿Cómo valido una dirección de email utilizando expresiones regulares?

R:

Versión Simple
Código PHP:

<html>
<
head>

<
script language="javascript" type="text/javascript" defer>
function 
validaEmail(email)
{
var 
re  = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if (!
re.test(email)) {
    
alert ("Dirección de email inválida");
    return 
false;
}
return 
true;
}
</script>
</head>

<body>
<center>
<form name="email" onSubmit="return validaEmail(this.email.value);">
Email:  <input type="text" name="email"><br>
<input type=submit value="Submit">
</form>
</center>
</body>
</html> 

Versión Compleja:
Código PHP:

<html>
<
head>

<
script language="javascript" type="text/javascript" defer>
// Regexp creado por Sandeep V. Tamhankar ([email protected])

function emailCheck (emailStr) {

var 
emailPat=/^(.+)@(.+)$/;
var 
specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
var 
validChars="\[^\\s" specialChars "\]";
var 
quotedUser="(\"[^\"]*\")";
var 
ipDomainPat=/^[(d{1,3}).(d{1,3}).(d{1,3}).(d{1,3})]$/;
var 
atom=validChars '+';
var 
word="(" atom "|" quotedUser ")";
var 
userPat=new RegExp("^" word "(\\." word ")*$");
var 
domainPat=new RegExp("^" atom "(\\." atom +")*$");
var 
matchArray=emailStr.match(emailPat);
if (
matchArray==null) {
    
alert("La dirección de correo parece ser inválida (verifique las @ y .)")
    return 
false
}
var 
user=matchArray[1]
var 
domain=matchArray[2]

if (
user.match(userPat)==null) {
    
alert("El nombre de usuario parece ser inválido.")
    return 
false
}

var 
IPArray=domain.match(ipDomainPat)
if (
IPArray!=null) {
      for (var 
i=1;i<=4;i++) {
        if (
IPArray[i]>255) {
            
alert("La dirección IP de destino es inválida!")
        return 
false
        
}
    }
    return 
true
}

var 
domainArray=domain.match(domainPat)
if (
domainArray==null) {
    
alert("El dominio no parece ser válido.")
    return 
false
}
var 
atomPat=new RegExp(atom,"g")
var 
domArr=domain.match(atomPat)
var 
len=domArr.length
if (domArr[domArr.length-1].length<|| 
    
domArr[domArr.length-1].length>3) {
   
alert("Las direcciones deben terminar con dominios de tres letras, o el código de país de dos letras.")
   return 
false
}

if (
len<2) {
   var 
errStr="Dominio Inválido!";
   
alert(errStr)
   return 
false
}

return 
true;
}
</script>
</head>


<body>
<center>
<form name="email" onSubmit="return emailCheck(this.email.value);">
Email:  <input type="text" name="email"><br>
<input type=submit value="Submit">
</form>
</center>
</body>
</html> 

Funciona en:
- IE 4+
- Netscape 4+
- Opera 5+
- Mozilla 0.8+ / Netscape 6+

caricatos 01/01/2003 13:40

86.- Ventanas solo como pop-up
 
P: ¿Como puedo hacer para que la pagina solo se pueda abrir como popup, y si se abre en modo normal se cierre?? (enlace )

R:

Código:

<body onLoad="if (!opener) window.close()">
Saludos :arriba:

Kaopectate 06/01/2003 13:11

87.- Detección de texto seleccionado
 
P: ¿Como puedo capturar el texto que está seleccionado dentro de mi página?

Créditos: Tomado de una respuesta de DanielRey

R: [ver ejemplo]

Código PHP:

<html>
 <
head>
  <
a name="#1">
  <
script language="JavaScript">
   function 
sele() {
    
a=document.selection.createRange();
    
alert("Tipo de selección: " document.selection.type "\nTexto seleccionado: " a.text);
   }
  
</script>
 </head>
 <body>
  <form name="frm">
   <table border="0">
    <tr>
     <td align="right">
      input:
     </td>
     <td>
      <input type="textInput" name="txt">
     </td>
    </tr>
    <tr>
     <td align="right">
      textarea:
     </td>
     <td>
      <textarea name="txtArea"></textarea>
     </td>
    </tr>
    <tr>
     <td align="right">
      Link:
     </td>
     <td>
      <a href="#1">Enlace</a>
     </td>
    </tr>
    <tr>
     <td align="right">
      Select:
     </td>
     <td>
      <select>
       <option>Uno</option>
       <option>Dos</option>
       <option>Tres</option>
      </select>
     </td>
    </tr>
    <tr>
     <td align="right">
      Párrafo:
     </td>
     <td>
      Esto es un párrafo de donde también se puede seleccionar texto.
     </td>
    </tr>
    <tr>
     <td align="center" colspan="2">
      <a href=JavaScript:sele()>Ver texto seleccionado</a> 
     </td>
    </tr>
  </form>
 </body>
</html> 


chivi 07/01/2003 11:33

88. Detectar Resolución y Redireccionar
 
P: ¿Cómo puedo mostrar la resolución de la pantalla del usuario y con un simple enlace redireccionarle a la página apropiada?

R:
Código PHP:

<html>
<
head>
<
script>
var 
resurl
if ((screen.width == 800) && (screen.height == 600)){
res="800x600"
url="800x600.htm"}
else if ((
screen.width == 1024) && (screen.height == 768)){
res="1024x768";
url="1024x768.htm"}
else if ((
screen.width == 1152) && (screen.height == 864)){
res="1152x864";
url="1152x864.htm"}
else if ((
screen.width == 1280) && (screen.height == 1024)){
res="1280x1024";
url="1280x1024.htm"}
else{
window.location.href "otra.htm"}
function 
Entrar(){
window.location.href=url}
</script>
</head>
<body>
Tu Resolución de Pantalla es: <b><script>document.write(res)</script></b><br>
<a href="javascript:Entrar()">Acceda a la página correspondiente a tu resolución</a>
</body>
</html> 


KarlanKas 13/01/2003 12:11

89. Reloj en la barra de estado
 
P.- ¿Cómo puedo poner un reloj en la barra de estado?
R.- Con este código:
ver ejemplo
Código PHP:

<HTML>
<
TITLE>Status Hora y día</TITLE>
<
HEAD>

<
SCRIPT LANGUAGE="JavaScript">

<!-- 
Script by:  Francis Woodhouse (francis@contessa.u-net.com) -->

<!-- 
function 
runClock() {
theTime window.setTimeout("runClock()"1000);
var 
today = new Date();
var 
displaytoday.toLocaleString();
status=display;
}
//  -->
</SCRIPT>


<body onLoad="runClock()">

</body>
</html> 


epa2 14/01/2003 03:32

90.- Buenos días amigo mio
 
P: ¿Como puedo dar los buenos días a mi amigo o visitante y que siempre que entre a mi sitio le de los buenos días?

R: Con una cookie

Créditos: Unknown

R: [Examina este ejemplo]

Código PHP:

<script language="Javascript">
<!--
/*-- for(unknown){ [email][email protected][/email] } --
Do N't Move Here is unKnown Production's --*/
var today = new Date();
var 
hora=today.getHours(); 
var 
expiry = new Date(today.getTime() + 28 24 60 60 1000); // 28 dias
function setCookie(namevalue
{
document.cookie=name "=" escape(value) + "; expires=" expiry.toGMTString();
}

function 
lee(valor)
{
document.cookie.search(RegExp("("+valor+"=)([^;]*)(;*)","gi"))
return 
unescape(RegExp.$2)
}
if(
lee('usass'))
var 
usuario lee('usass')
else{
var 
u=prompt("Introduce tu Nombre","")
if(
u){setCookie('usass',u);usuario=u}
else{
usuario "Usuario"}

if (
hora<6)
alert(usuario+" Hoy has madrugado mucho...¿O no te has acostado?");
else if (
hora<12)
alert(usuario+" Buenos d&iacute;as");
else if (
hora<=18)
alert("Buenas Tardes "+usuario);
else 
alert("Buenas Noches "+usuario);
</script> 


KarlanKas 14/01/2003 04:54

91. Redireccionar página pasados unos segundos
 
P.- ¿Cómo puedo redireccionar una página a otra pasados unos segundos?
R.- Con este código:

Código PHP:

<html>
<
head>

</
head>

<
body style="font:bold 10px/15px verdana;color:navy">
<
script>
//Script original de KarlanKas para forosdelweb.com


var segundos=3
var direccion='http://www.webareyou.com'
var mensaje="Nos hemos trasladado."

milisegundos=segundos*1000
window
.setTimeout("window.location.replace(direccion);",milisegundos);
document.write(mensaje+"  Si pasados "+segundos" segundos no es redireccionado pinche <a href='"+direccion+"'>aquí</a>.");
</script>

</body>
</html> 


haven 14/01/2003 16:42

92 - Impedir que seleccionen mas de dos checkbox
 
P: Impedir que seleccionen mas de dos checkbox en un formulario

R:

Código PHP:


<script>

function 
countChoices(obj) {
max 1// max. number allowed at a time

obj.form.PollVote1.checked// your checkboxes here
obj.form.PollVote2.checked;

// add more if necessary

count = (0) + (0);
// If you have more checkboxes on your form
// add more (box_ ? 1 : 0) 's separated by '+'

if (count max) {
alert("Atencion! Solo puede seleccionar " max " opcion! \Quite una de ellas si quiere seleccionar otra.");
obj.checked false;
}
}


</script>

Y el campo checkbox es de la forma

<form name="form">

<input type="checkbox" value="1" name="PollVote1" onClick="countChoices(this)">

<input type="checkbox" value="2" name="PollVote2" onClick="countChoices(this)">

<form>

Si tienes los campos de esta forma (gracias tunait):

<form name="form">

<input type="checkbox" value="1" name="PollVote" onClick="countChoices(this)">

<input type="checkbox" value="2" name="PollVote" onClick="countChoices(this)">

<form>


deberás poner:

a = obj.form.PollVote[1].checked; // your checkboxes here
b = obj.form.PollVote[2].checked; 

Un saludo

DanielRey 15/01/2003 14:55

93 - Copiar el texto seleccionado
 
P: Copiar el texto que se ha seleccionado en la página.

R:
Código:

<!-- TWO STEPS TO INSTALL COPY SELECTED TEXT:

  1.  Copy the coding into the HEAD of your HTML document
  2.  Add the last code into the BODY of your HTML document  -->

<!-- STEP ONE: Paste this code into the HEAD of your HTML document  -->

<HEAD>

<!-- This script and many more are available free online at -->
<!-- The JavaScript Source!! http://javascript.internet.com -->
<!-- Original:  Raul Macias ([email protected] ) -->
<!-- Web Site:  http://members.cox.net/raulhmacias/ -->
<SCRIPT LANGUAGE="JavaScript">
<!-- Begin
function copyit(theField) {
        var selectedText = document.selection;
        if (selectedText.type == 'Text') {
                var newRange = selectedText.createRange();
                theField.focus();
                theField.value = newRange.text;
        } else {
                alert('select a text in the page and then press this button');
        }
}
//  End -->
</script>

</HEAD>

<!-- STEP TWO: Copy this code into the BODY of your HTML document  -->

<BODY>

<!-- This script and many more are available free online at -->
<!-- The JavaScript Source!! http://javascript.internet.com -->
<!-- Original:  Raul Macias ([email protected] ) -->
<!-- Web Site:  http://members.cox.net/raulhmacias/ -->
<form name="it">

<p>This script allows you to select text on a web page and then copy it into a text box. Neat!</p>
<div align="center">
<input onclick="copyit(this.form.select1)" type="button" value="Press to copy the highlighted text" name="btnCopy">
<p>
<textarea name="select1" rows="4" cols="45"></textarea>
</div>
</form>

<p><center>
<font face="arial, helvetica" size"-2">Free JavaScripts provided<br>
by <a href="http://javascriptsource.com">The JavaScript Source</a></font>
</center><p>

<!-- Script Size:  1.69 KB -->


Kaopectate 29/01/2003 22:17

94.- Tipo y versión del navegador
 
P: ¿Como puedo saber el tipo de navegador y la versión del mismo?

R: [ver ejemplo]

La función getBrowserName() retornará uno de los siguientes valores:
- ie = Internet Explorer
- ns = Netscape
- op = Opera
- mo = Mozilla

La función getBrowserVersion() retornará la versión del navegador correspondiente.

Código PHP:

<html>
 <
head>
  <
script LANGUAGE="JavaScript">

   var 
sBrowser;
   var 
sVersion;

   function 
setBrowserType(){
    var 
aBrowFull = new Array("opera""msie""netscape""gecko""mozilla");
    var 
aBrowVers = new Array("opera""msie""netscape""rv",    "mozilla"   );
    var 
aBrowAbrv = new Array("op",    "ie",   "ns",       "mo",    "ns"   );
    var 
sInfo navigator.userAgent.toLowerCase();;

    
sBrowser "";
    for (var 
0aBrowFull.lengthi++){
     if ((
sBrowser == "") && (sInfo.indexOf(aBrowFull[i]) != -1)){
      
sBrowser aBrowAbrv[i];
      
sVersion String(parseFloat(sInfo.substr(sInfo.indexOf(aBrowVers[i]) + aBrowVers[i].length 1)));
     }
    }
   }

   
setBrowserType();

   function 
getBrowserName(){
    return 
sBrowser;
   }

   function 
getBrowserVersion(){
    return 
sVersion;
   }

  
</script>
 </head>
 <body>
  <script language="JavaScript">
   setBrowserType();
   document.write("Browser: " + getBrowserName() + "<br>");
   document.write("Versión: " + getBrowserVersion() + "<br><br>" );
  </script>
 </body>
</html> 

Por favor, cualquier observación sobre este script o cualquier reporte de uso, incluirlo en este mensaje.

epa2 30/01/2003 02:41

95.- Buscador Web en mi sitio

P: ¿Como pongo un buscador Web en mi sitio?

R: Con este código.

Creditos: No me acuerdo de donde lo bajé pero ahí pongo el autor. / Script by Jari Aarniala [www.mbnet.fi/~foo -- [email protected]]

Ver ejemplo: Pulsa aqui pecadoooorr

NOTA: Si este script estuviese repe, favor de hacermelo saber. Gracias.

Código:

<body>
<tr>
    <td width="100%">
    <p align="center">&nbsp;</td>
</tr>
<tr>
    <td width="100%">&nbsp;</td>
  </tr>
  <tr>
    <td width="100%" style="text-indent: 0" height="19">
    <span lang="es"><script language="JavaScript">
<!--

//
// Script by Jari Aarniala [www.mbnet.fi/~foo -- [email protected]]
//
// This script makes it easy to choose with which search engine
// you`d like to search the net. You may use this if you keep this
// text here...
//

function startSearch(){
searchString = document.searchForm.searchText.value;
if(searchString != ""){
searchEngine = document.searchForm.whichEngine.selectedIndex + 1;
finalSearchString = "";

if(searchEngine == 1){
finalSearchString = "http://www.altavista.digital.com/cgi-bin/query?pg=q&what=web&fmt=.&q=" + searchString;
}
if(searchEngine == 2){
finalSearchString = "http://av.yahoo.com/bin/query?p=" + searchString + "&hc=0&hs=0";
}
if(searchEngine == 3){
finalSearchString = "http://www.excite.com/search.gw?trace=a&search=" + searchString;
}
if(searchEngine == 4){
finalSearchString = "http://www.hotbot.com/?SW=web&SM=MC&MT=" + searchString + "&DC=10&DE=2&RG=NA&_v=2&act.search.x=89&act.search.y=7";
}
if(searchEngine == 5){
finalSearchString = "http://www.infoseek.com/Titles?qt=" + searchString + "&col=WW&sv=IS&lk=noframes&nh=10";
}
if(searchEngine == 6){
finalSearchString = "http://www.lycos.com/cgi-bin/pursuit?adv=%26adv%3B&cat=lycos&matchmode=and&query=" + searchString + "&x=45&y=11";
}
if(searchEngine == 7){
finalSearchString = "http://netfind.aol.com/search.gw?search=" + searchString + "&c=web&lk=excite_netfind_us&src=1";
}

location.href = finalSearchString;
}
}


// -->
    </script>

<basefont face="Verdana, Arial, sans-serif">

</span>

<form name="searchForm">

<div align="center">
  <center>

<table width=323 border="2" cellpadding=3 cellspacing=0 bgcolor=444444 style="border-collapse: collapse" bordercolor="#111111">

<tr>
<td bgcolor=lightblue width="148"><font size="1"><span lang="es">Buscar por:</span></font><font size=1 face="Verdana, Arial, sans-serif"><span lang="es"><br>

</span>
<td bgcolor=lightblue width="96"><font size="1"><span lang="es">Buscar desde:</span></font><span lang="es"><td bgcolor=lightblue width="90">

<tr>
<td bgcolor=navajowhite width="148">
<input style="background: dddddd" name="searchText" type="text" size="20">
<td bgcolor=navajowhite width="96">
<select style="background: dddddd" name="whichEngine">
<option selected>Altavista
<option>Yahoo!
<option>Excite
<option>Hotbot
<option>Infoseek
<option>Lycos
<option>AOL Netfind
</select>
<td bgcolor=navajowhite width="90">
<input type="button" value="Buscar " onClick="startSearch()">

</select>
</table>
  </center>
</div>
</form>

</span>&nbsp;</td>
  </tr>
</body>
</html>


JavierB 31/01/2003 11:40

96.- Quitar recuadro punteado de enlace

P: ¿Como puedo quitar el recuadro de puntos de un enlace activo?

R: Con este código.

Creditos: unKnown, con modificación de Caricatos para que funcione también en Netscape.
Código PHP:

<html>
<
head>
<
script language="JavaScript">
    function 
prende() {
    
anclas=document.getElementsByTagName("a").length;
    for (
i=0;i<anclas;i++)
    
document.getElementsByTagName("a").item(i).onfocus=new Function("if(this.blur)this.blur()")
    }
</script>
</head>

<body onLoad="prende()">
<a href="#">Enlace1</a> <a href="#">Enlace2</a> <a href="#">Enlace3</a> 
</body>
</html> 


Kaopectate 01/02/2003 22:20

97.- Impedir que lean el código fuente
 
P: ¿Como puedo impedir que lean el código de mi página?

Créditos: itatpc

R: Independientemente de mi posición ante la idea de programar para que otros no lean, publico esta solución que sin lugar a dudas es una "pregunta frecuente". El hilo original fué publicado por itatpc y en él se discuten algunas posibilidades adicionales de seguridad.

Añadir esta línea en alguna parte de la cabecera:

Código PHP:

<frame>
<
noframes>
</
frame>
</
noframes

NOTA: Yanix comenta lo siguiente:
Cita:

Recuerden que solamente sirve si graban la pagina como web page completa (la cual te graba los css, javascripts, etc).
Si le cambian el tipo al momento de guardarla a Web HTML only, ese snip no va a funcionar. (probado en IE 5.5)

KarlanKas 05/02/2003 03:25

98 (comete un bizcocho). Evitar que vuelvan a la página anterior.
 
P.-¿Cómo conseguir que no funcione el botón atrás del navegador?
R.- Con este código, que debes poner en la página anterior, por lo que sólo podrás evitar que vuelva atrás si la página anterior es tuya.

Código PHP:

<script>
//Script original de KarlanKas para forosdelweb.com

// /////////////// EN EL HEAD ///////////////////

if (history.forward(1)){location.replace(history.forward(1))}

</script> 


DanielRey 05/02/2003 06:45

99 - Poner texto vertical (sólo IE 5.0 +)
 
Poner texto vertical, al revés, rotarlo, que vuele, lo que quieras.

Para ver el original:
http://www.24fun.com/downloadcenter/...extwheel2.html
No te lo pierdas!!! es alucinante.

Código PHP:

<center>
<
OBJECT ID="pepe"
 
CLASSID="CLSID:369303C2-D7AC-11d0-89D5-00A0C90833E6"
 
STYLE="position:relative; width:300px; height:200 px">
        <
PARAM NAME="Line0001" VALUE="SetLineStyle(1)">
        <
PARAM NAME="Line0002" VALUE="SetLineColor(0,0,0)">
    <
PARAM NAME="Line0003" VALUE="SetFillColor(255,128,0)">
    <
PARAM NAME="Line0004" VALUE="SetFont('Arial', 20, 0, 0, 1, 0)">
    <
PARAM NAME="Line0005" VALUE="Text('Foros del Web', 0, 0, 0)">
    </
OBJECT>
<
script>
function 
eje1() {
  
pepe.Rotate(1500);
}

function 
eje2() {
  
pepe.Rotate(0150);
}

function 
eje3() {
  
pepe.Rotate(0015);
}
</script>
<input type=button onClick=eje1(); value="eje 1">
<input type=button onClick=eje2(); value="eje 2">
<input type=button onClick=eje3(); value="eje 3">
<!--
SetLineStyle(valor)
valor=0 => Sin línea de contorno de texto.
valor=1 => Línea continua
valor=2 => Linea discontinua

SetLineColor(R, G, B)
Intensidad del color (R=rojo, G=verde, B=azul)
de 0 a 255 de la linea de contorno de texto.

SetFillColor(R, G, B)
Intensidad del color (R=rojo, G=verde, B=azul)
del relleno del texto

SetFont('font', Tam, B, It, Sub, Tach)
font: Arial, Verdana, etcétera
Tam: El tamaño de la letra
B: 0=> Normal; 1=> Bold.
It: 0=> Normal; 1=> Itálica.
Sub: 0=> Normal; 1=> Subrayado
Tach: 0=> Normal; 1=> Tachado

Text('texto', H, V, R)
texto: El texto que se muestra
H: Posición horizontal inicial
V: Posición vertical inicial
R: Rotación plana inicial
--> 


Kaopectate 06/02/2003 09:31

100.- Usos del método open()
 
P: ¿Que atributos puedo usar en el método open()?

R: El método open() tiene la siguiente sintaxis: [Ver wizard]

Código:

open(sURL, sNombre, sAtributos, bHistoria);
Donde:

sURL: Indica la dirección de la página a abrir.
sNombre: Nombre de la ventana (util para abrir una segunda dirección sobre la misma ventana.
sAtributos: Definidos posteriormente.
bHistoria: Si la nueva dirección se abre sobre una ventana existente, este indicador dice si debe o no añadirse al historial.

Lista de atributos utilizables en el método open (actualizada con indicadores de compatibilidad hasta NS-4 e IE-5).

Atributo: alwaysLowered (NS-4)
Valor: Se usa sin igualarlo a ningún valor
Notas: Indica que la ventana debería permanecer siempre al final de la pila de ventanas.

Atributo: alwaysRaised (NS-4)
Valor: Se usa sin igualarlo a ningún valor
Notas: Indica que la ventana debería permanecer siempre en el tope de la pila de ventanas.

Atributo: channelMode (IE-4)
Valor: Se usa sin igualarlo a ningún valor
Notas: Indica si la ventana deberá ser presentada en modo "Channel".

Atributo: dependent (NS-4)
Valor: Yes/No
Notas: Si una ventana es no dependiente, podrá sobrevivir luego de que su creador sea cerrado.

Atributo: directories (NS-4)
Valor: Yes/No
Notas: Controla la apariencia del toolbar personal de Netscape.

Atributo: fullscreen (IE-4)
Valor: Se usa sin igualarlo a ningún valor
Notas: Bajo Windows, MSIE llena la pantalla con la ventana.

Atributo: height (NS-2,IE-4)
Valor: Número.
Notas: Altura de la ventana.

Atributo: hotkeys (NS-4)
Valor: Yes/No
Notas: Colocando este valor a "no", deshabilitará la mayoría de los shortcuts de teclado aparte de la opción quit.

Atributo: innerHeight (NS-4)
Valor: Número.
Notas: Ajusta la altura interna de la ventana al valor dado.

Atributo: innerWidth (NS-4)
Valor: Número.
Notas: Ajusta el ancho interno de la ventana al valor dado.

Atributo: left (NS-4,IE-4)
Valor: Número.
Notas: Posición izquierda de la ventana.

Atributo: location (NS-2,IE-4)
Valor: Yes/No.
Notas: Barra de direcciones visible/invisible.

Atributo: menubar (NS-2)
Valor: Yes/No.
Notas: Barra de menú visible/invisible.

Atributo: outerHeight (NS-4)
Valor: Número.
Notas: Ajusta la altura externa de la ventana al valor dado.

Atributo: outerWidth (NS-4)
Valor: Número.
Notas: Ajusta el ancho externo de la ventana al valor dado.

Atributo: resizable (NS-2,IE-4)
Valor: Yes/No.
Notas: La ventana puede o no ser cambiada de tamaño.

Atributo: screenX (NS-4)
Valor: Número.
Notas: Nombre alterno para la posición izquierda de la ventana.

Atributo: screenY (NS-4)
Valor: Número.
Notas: Nombre alterno para la posición superior de la ventana.

Atributo: scrollbars (NS-2,IE-4)
Valor: Yes/No.
Notas: Pueden o no ser mostradas las barras de desplazamiento.

Atributo: status (NS-2,IE-4)
Valor: Yes/No.
Notas: Debe o no ser mostrada las barra de estado.

Atributo: toolbar (NS-2,IE-4)
Valor: Yes/No.
Notas: Debe o no ser mostrada las barra de herramientas.

Atributo: top (NS-4,IE-4)
Valor: Número.
Notas: Posición superior de la ventana.

Atributo: width (NS-2,IE-4)
Valor: Número.
Notas: Ancho de la ventana.

Atributo: z-lock (NS-4)
Valor: Se usa sin igualarlo a ningún valor
Notas: Indica que la ventana debería estar en una posición fija en la pila de ventanas.


Lanzando PopUps con JavaScript:

Si deseas conocer el modo correcto de abrir un popup usando JavaScript, te recomendamos este artículo (tomado de esta discusión). Creditos: ferent.


Algunos ejemplos frecuentes:

- Abrir una ventana en una ubicación específica:
open("ventana.htm", "nombre", "left=100,top=100,width=600,height=400");

- Abrir una ventana sin barra de herramientas, sin barra de dirección, sin barras de desplazamiento, sin barra de estatus:
open("ventana.htm", "nombre", "location=no,menubar=no,scrollbars=no,status=n o");

- Abrir una ventana fullscreen (solo Internet Explorer):
open("ventana.htm", "nombre", "fullscreen");

Para observaciones, actualizaciones o correcciones sobre este tema por favor ir al siguiente hilo.


La zona horaria es GMT -6. Ahora son las 23:48.

Desarrollado por vBulletin® Versión 3.8.7
Derechos de Autor ©2000 - 2025, Jelsoft Enterprises Ltd.