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/)

Panino5001 02/04/2007 04:55

251.-Selección en Textarea
 
P: Cómo seleccionar parte del contenido de un textarea sin usar el mouse?
R:
Código:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>ejemplo</title>
<script>
function sel(inicio,fin){
input=document.getElementById('area');
if(typeof document.selection != 'undefined' && document.selection){
tex=input.value;
input.value='';
input.focus();
var str = document.selection.createRange();
input.value=tex;
str.move('character', inicio);
str.moveEnd("character", fin-inicio);
str.select();
}
else if(typeof input.selectionStart != 'undefined'){
input.setSelectionRange(inicio,fin);
input.focus();
}
}
</script>
</head>

<body>
<form id="form1" name="form1" method="post" action="">
  <textarea name="area" cols="60" rows="10" id="area">esta es una prueba</textarea>
  <input type="button" name="Submit" value="seleccionar" onclick="sel(8,11)" />
</form>
</body>
</html>

Ejemplo probado en Safari, Explorer, Firefox y Ópera

caricatos 02/05/2007 02:28

Re: FAQs JavaScript
 
P: ¿Como recoger Datos por url?
R: Para datos simples se puede usar otro mensaje de estas FAQs: Recoger valores de un formulario, pero para recoger arrays se puede con el código de este mensaje: Recibiendo array por url

Pego a continuación una de las versiones (creo que la más corta):

Código:

function receptor()        {
        var entrada = new Object();
        if (location.href.indexOf("?") == -1) return;
        params = location.search.substr(1).split("&");
        for (var i = 0, total = params.length; i < total; i ++)        {
                pareja = params[i].split("="); dato = unescape(pareja[1]);
                switch        (typeof(entrada[pareja[0]]))        {
                        case "undefined": entrada[pareja[0]] = dato; break;
                        case "object": entrada[pareja[0]][entrada[pareja[0]].length] = dato; break;
                        case "string": temp = [entrada[pareja[0]], dato]; entrada[pareja[0]] = temp; break;
                }
        }
        for (i in entrada)        window[i] = entrada[i];
}

Saludos :arriba:

nicolaspar 13/05/2007 07:15

Re: FAQs JavaScript
 
Pregunta: Como reproducir un sonido con eventos?
Respuesta:
Código:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Reproducir sonido - By Nicolás Pardo 2007</title>

<script>
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

/*Namespaces*/
var Media = document.Media || {};
// funciones para cookies

Media.PlaySound = {
    MSIE: navigator.userAgent.indexOf("MSIE"),
    NETS: navigator.userAgent.indexOf("Netscape"),
    OPER: navigator.userAgent.indexOf("Opera"),
    cookieName:  "cookie_sound_active",
    imgOn: "images/ico_on.gif",
    imgOff: "images/ico_off.gif",
    Sound: "_sonido.wav",
    WriteCookie: function( name, value ){
        var expdate=new Date();
        expdate.setTime(expdate.getTime()+10*365*24*60*60*1000);
        document.cookie = name + "=" + escape (value) + "; expires=" + expdate.toGMTString();
    },
    ReadCookie: function( name ){
        var namearg = name + "=";
        var nlen = namearg.length;
        var clen = document.cookie.length;
        var i = 0;
        while (i < clen) {
            var j = i + nlen;
            if (document.cookie.substring(i, j) == namearg) {
                var endpos = document.cookie.indexOf (";", j);
                if (endpos == -1) endpos = document.cookie.length;
                return unescape(document.cookie.substring(j, endpos));
            }
            i = document.cookie.indexOf(" ", i) + 1;
            if (i == 0) break;
        }
        return null;
    },
    OnOffSound: function( img ){
        newValue = Media.PlaySound.ReadCookie( Media.PlaySound.cookieName ) == 1 || Media.PlaySound.ReadCookie( Media.PlaySound.cookieName ) == null  ? 0 : 1;
        img.src = newValue == 1 ? Media.PlaySound.imgOn : Media.PlaySound.imgOff;
        Media.PlaySound.WriteCookie( Media.PlaySound.cookieName, newValue );
    },
    SetMediaIE: function(){
        if((Media.PlaySound.MSIE>-1) || (Media.PlaySoundOPER>-1)) {
            document.write('<bgsound loop="0" name="MediaMyMediaObj" id="MediaMyMediaObj" >');
        }
    },
    PlayNow: function(){
    if( Media.PlaySound.ReadCookie( Media.PlaySound.cookieName ) == 1 || Media.PlaySound.ReadCookie( Media.PlaySound.cookieName ) == null ){
        obj = MM_findObj("MediaMyMedia");
            if((Media.PlaySound.MSIE>-1) || (Media.PlaySoundOPER>-1)) {
                obj = MM_findObj("MediaMyMediaObj");
                obj.src = Media.PlaySound.Sound;
            } else {
                obj = MM_findObj("MediaMyMediaDiv");
                obj.innerHTML = '<embed  src="'+Media.PlaySound.Sound+'" hidden="true" volume="200" loop="0" type="audio/midi" >';
            }
        }
    }
}

Media.PlaySound.SetMediaIE();
</script>
</head>
<body>
<a href="#"><img src="images/ico_on.gif" onclick="Media.PlaySound.OnOffSound(this)" border="0" /></a>
<br />

<div name="MediaMyMediaDiv" id="MediaMyMediaDiv" style="margin:0; width:0; height:0;"></div>
<input type="button" value="dame" onclick="Media.PlaySound.PlayNow()" />
</body>
</html>

http://snipplr.com/view.php?codeview&id=2384

Testeado en IE y FF

nicolaspar 13/05/2007 07:23

Re: FAQs JavaScript
 
Pregunta: Puedo eliminar la selección (encuadre) de los A?. Un ejemplo para explicar mejor el problema:

Código:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Documento sin t&iacute;tulo</title>

</head>

<body>
<a href="asa.hh">Test link</a>
</body>
</html>

Guarden esto, y verán que al hacer TAB con el teclado sobre el documento el links se marcan. Muy molesto cuando tenemos botoneras con imagenes, o imagenes mapeadas, también aplica a anclas que quedan marcadas al darles clic.


Respuesta
Código:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Un Focus by Nicolás Pardo</title>
<script>
function unFocusA() {
    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="unFocusA()">
<a href="asa.hh">Test link</a>
</body>
</html>


nicolaspar 13/05/2007 07:35

Re: FAQs JavaScript
 
Pregunta: Como avisarle al usuario que tiene un bloqueador de popup?
Respuesta:
Código:

function popup(url,ancho,alto,id,extras){
    if(navigator.userAgent.indexOf("Mac")>0){ancho=parseInt(ancho)+15;alto=parseInt(alto)+15;}
    var left = (screen.availWidth-ancho)/2;
    var top = (screen.availHeight-alto)/2;
    if(extras!=""){extras=","+extras;};
    var ventana = window.open(url,id,'width='+ancho+',height='+alto+',left='+left+',top='+top+',screenX='+left+',screenY='+top+extras);
    var bloqueado = "AVISO:\n\nPara ver este contenido es necesario que desactive\nel Bloqueo de Ventanas para este Sitio."
    //var bloqueado = "WARNING:\n\nIn order to use this functionality, you need\nto deactivate Popup Blocking."
    if(ventana==null || typeof(ventana.document)=="undefined"){ alert(bloqueado) }else{ return ventana; };
}

Notas:
1- Los bloqueadores generalmente trabajan sobre eventos que no son directos del usuario, ejemplo onload, con esto digo que no es necesario para eventos como ser onclick.
2- Hay bloqueadores que lo que hacen es abrir el popup y luego cerrarlo, para ellos esta función no aplica.

nicolaspar 13/05/2007 07:41

Re: FAQs JavaScript
 
Pregunta: Hay algo para que me reemplaze los saltos de lineas por br?
Respuesta:
Código:

function nl2br(text){
    text = escape(text);
    if(text.indexOf('%0D%0A') > -1){
        re_nlchar = /%0D%0A/g ;
    }else if(text.indexOf('%0A') > -1){
        re_nlchar = /%0A/g ;
    }else if(text.indexOf('%0D') > -1){
        re_nlchar = /%0D/g ;
    }
    return unescape( text.replace(re_nlchar,'<br />') );
}


stock 05/06/2007 09:11

Re: FAQs JavaScript
 
Pregunta: como puedo hacer un carrusel de imagenes?
Respuesta: un carrusel de imagenes, o un slideshow, es muy sencillo de realizar, simplemente necesitas ir sustitullendo las imagenes en contenedores, y luego hacer una transicion, mas explicacion al respecto en el siguiente link:

http://www.crysfel.com/index.php/200...l-de-imagenes/

have funnnnnnnnn :adios:

juan-raro 06/07/2007 02:18

No imprimir ciertas partes de una página.
 
Pregunta: Como imprimir una página pero no imprimir el menu u otros elemenos.
Respuesta: con este sencillo código indicas lo que no debe ser impreso.

Cita:

<script type="text/javascript">

function removeelements(){
var removeclass="remove"
var alltags=document.getElementsByTagName("*")
for (i=0; i<alltags.length; i++){
if (alltags[i].className==removeclass)
alltags[i].style.display="none"
}
}

function revertback(){
setTimeout("window.location.reload()",50)
}

window.onbeforeprint=removeelements
window.onafterprint=revertback

</script>

<body>
<p class="remove"><img src="bannerad.gif"></p>
<table border="0" width="100%" cellspacing="0" cellpadding="0">
<tr>
<td width="20%" class="remove">Left Nav Bar</td>
<td width="80%">Main Content</td>
</tr>
</table>

ric18 25/07/2007 16:19

Validaciones ..
 
P ¿Cómo puedo validar campos de texto y a la vez un upload?

R

Mucho me ha ayudado este foro, asi que aquí les dejo una validación con Javascript, valida los campos de texto y las extenciones para hacer un upload.


f
Código PHP:

unction valida ()    
    {        
    
    if(
document.form.nombre_usuario.value ==''){
    
alert("Por favor introduzca su nombre.");
    
document.form.nombre_usuario.focus();
    return; }    
    
    if(
document.form.apellidos_usuario.value ==''){
    
alert("Por favor introduzca sus apellidos.");
    
document.form.apellidos_usuario.focus();
    return; }    

    if(
document.form.correo.value == ''){
    
alert("Por favor introduzca su email.");
    
document.form.correo.focus();
    return; }
    
    if ((
document.form.correo.value.indexOf ('@', 0) == -1)||(document.form.correo.value.length < 5)||(document.form.correo.value.indexOf ('.', 6) == -1)){ 
    
alert("Por favor, introduzca una dirección de correo electrónico válida."); 
    
document.form.correo.focus();
    return (
false); }    


//Valida el upload de los archivos para que sólo envíe los archivos con extención requerida 
            
var A = "false"
var c = document.getElementById('file').value;
var 
llarg = c.length;
var 
extension = c.substring(c.length-3,c.length)

    if (
extension == "cvs" || c == "") {
    
A = "true";
     }
    else if (
document.getElementById("file").value.indexOf('.cvs',0)== -1)
    {
    
//document.getElementById("SecondTrack").value.indexOf('.gif',0)== -1){
    
alert("El archivo no tiene una extensión correcta, verifique");
    
document.getElementById("file").select();
    
document.getElementById("file").focus();
    return (
false);
    } 


Lengsel 09/10/2007 04:01

Re: 37.- text que admita solo numeros
 
Cita:

Iniciado por atlante (Mensaje 264445)
P : Como se puede impedir que se ingrese un dato no numerico ?

R :
Código PHP:

<HTML>
<
HEAD>
<
TITLE></TITLE>
</
HEAD>
<
script language="javascript">
<!--
function 
LP_data(){
var 
key=window.event.keyCode;//codigo de tecla.
if (key < 48 || key > 57){//si no es numero 
window.event.keyCode=0;//anula la entrada de texto.
}}
-->
</script> 

<basefont face=verdana size=2>
<BODY>
<form name="miForm">
<input type=text name="num" onKeypress="LP_data()"><br><br>
<input type="button" value="enviar" onClick="LP_box()">
</form>
</BODY>
</HTML>

hola, este es mi primer post. escribo citando porque no se como es el protocolo. mejore este codigo, y lo posteo aqui para que lo puedan publicar y otras personas puedan usarlo.
la solucion que tienen es solo para internet explorer, sólo acepta numeros del teclado (NO numpad), esta version soluciona eso...

Código PHP:

<html>
<
head>
<
title>valida solo numeros y punto decimal</title>
<
script language="javascript">
function 
filtro(evento) {
var 
keyCode = evento.which ? evento.which : evento.keyCode;
var 
valido = "1234567890abcdefghi`n¾.";
keychar = String.fromCharCode(keyCode); //alert(keychar);
return (valido.indexOf(keychar) != "-1") || keyCode == 8;
/* NOTA:
la variable 'valido' contiene todos los caracteres que corresponden a numeros
sí, numeros!, para ver que caracter es la tecla que presionan, descomenten 'alert(keychar);'
despues, verifico que la tecla que se presione, corresponda a algun caracter de la cadena, si
es asi, entonces se devuelve true y el caracter aparece en el textbox, sino, envio keyCode=8 (backspace) y se borra.
Es verdad que acepta mas de un punto decimal, pero eso ya es algo menor

espero les sea de utilidad

saludos :)
*/
}
</script>
</head>
<body>
<input name="textfield" type="text" id="textfield" onKeyDown="return filtro(event)">
</body>
</html> 


tunait 10/12/2007 03:59

Rotador de banners
 
P.- ¿Cómo puedo realizar un rotador de banners sencillo?

R.- Este es un mini software gratuito que genera el código javascript necesario para hacer un rotador de banners.

http://gitana2007.blogspot.com/2007/...avascript.html

Se puede hacer una descarga directa desde aquí
http://rapidshare.com/files/72465750...r_1_0_0_11.zip


el codigo JS que genera el soft está publicado en:
http://gitana2007.blogspot.com/2007/...e-banners.html

El soft ha sido desarrollado por TurKa :arriba::cool:

Panino5001 07/01/2008 11:52

Buscar dentro de la página
 
P: Cómo hacer un buscador que resalte, en el texto de la página, coincidencias con una cadena de búsqueda?

R:

Código:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>BUSCADOR</title>
<script>
String.prototype.preg_quote=function(){
        p= /([:.\+*?[^\]$(){}=!<>|:)])/g;
        return this.replace(p,"\\$1");
}
function buscar(cadena){
        resetear();
    if(!cadena.length)return;
        var info3;
        cadena=cadena.preg_quote();
        var patron=new RegExp(cadena+'(?!\}\})','gim');
        var espacio=/^\s$/;
        var el=document.getElementsByTagName('html')[0].getElementsByTagName('*');
        for(var i=0;i<el.length;i++){
                if(el[i].hasChildNodes && el[i].nodeName.toLowerCase()!='title' && el[i].nodeName.toLowerCase()!='script' && el[i].nodeName.toLowerCase()!='meta' && el[i].nodeName.toLowerCase()!='link' && el[i].nodeName.toLowerCase()!='style'){
                        var tt=el[i].childNodes;
                        for(var jj in tt){
                                if(tt[jj].nodeType==3 && !espacio.test(tt[jj].nodeValue)){
                                        patron.lastIndex = 0;
                                        if(info3=patron.exec(tt[jj].nodeValue)){
                                                tt[jj].nodeValue=tt[jj].nodeValue.replace(patron,'{{'+tt[jj].nodeValue.substr(info3['index'],cadena.length)+'}}');
                               
                                        }
                                }

                        }               
                }
        }
        document.getElementsByTagName('body')[0].innerHTML=document.getElementsByTagName('body')[0].innerHTML.split('}}').join('</span>').split('{{').join('<span style="background-color: #FFFF99">');
}
function resetear(){
        original=document.getElementsByTagName('body')[0].innerHTML=original;
}
window.onload=function(){
        original=document.getElementsByTagName('body')[0].innerHTML;
}
</script>
</head>

<body>
<form id="form1" name="form1" method="post" action="">
  <input name="cadena" type="text" id="cadena" />
  <input type="button" name="Button" value="buscar" onclick="buscar(cadena.value)" />

</form>

ver Buscador simple
<div>sí, dije buscador <div id="pepe">buscador <span> y
      metemos otra vez la palabra buscador} a ver /a qué pasa</span><span>algo
      más </span>y
      esto fuera del span y dentro de div </div>
</div>
y si ponemos buscador fuera otra vez?
</body>
</html>


caricatos 21/02/2008 01:23

Re: FAQs JavaScript
 
P ¿Como muestro un gif animado mientras se carga una imagen o un iframe?
R
Son necesarias 3 cosas... una de ellas es una capa con ese gif animado que en principio esté oculta, un evento que lo muestre que sería un botón o un enlace, y por último el evento de carga del iframe o imagen para volverla a ocultar:
Código:

<html>
<body>
<a onclick="document.getElementById('cargando').style.visibility = 'visible'"
href="http://www.forosdelweb.com" target="destino" >foros del web</a>
<br />
<a onclick="document.getElementById('cargando').style.visibility = 'visible'"
href="http://www.maestrosdelweb.com" target="destino" >maestros del web</a>

<br />
<div style="position: relative" >
<iframe name="destino" style="width: 300px; height: 300px"
onload="document.getElementById('cargando').style.visibility = 'hidden'" ></iframe>
<div id="cargando"
 style="position: absolute; top: 0; left: 0; width: 300px; height: 300px; background: white url(../dibujos/indicator.gif) no-repeat center center; visibility: hidden">
</div>
</body>
</html>


edualven 15/03/2008 16:36

Re: 123.- Resta de fechas [corrección un par de errores]
 
¿Como puedo saber la cantidad de días, meses y años que hay entre dos fechas? --> He encontrado 2 bugs, en el codigo a contiuación el error encontrado y las dos funciónes modificadas.

Código PHP:

<html>
 <
head>
  <
script language="JavaScript">
   function 
cerosIzq(sVal, nPos){
    var 
sRes = sVal;
    for (var 
i = sVal.length; i < nPos; i++)
     
sRes = "0" + sRes;
    return 
sRes;
   }

   function 
armaFecha(nDia, nMes, nAno){
    var 
sRes = cerosIzq(String(nDia), 2);
    
sRes = sRes + "/" + cerosIzq(String(nMes), 2);
    
sRes = sRes + "/" + cerosIzq(String(nAno), 4);
    return 
sRes;
   }

   function 
sumaMes(nDia, nMes, nAno, nSum){
    if (
nSum >= 0){
     for (var 
i = 0; i < Math.abs(nSum); i++){
      if (
nMes == 12){
       
nMes = 1;
       
nAno += 1;
      } else 
nMes += 1;
     }
    } else {
     for (var 
i = 0; i < Math.abs(nSum); i++){
      if (
nMes == 1){
       
nMes = 12;
       
nAno -= 1;
      } else 
nMes -= 1;
     }
    }
    return 
armaFecha(nDia, nMes, nAno);
   }

   
/*Esta función no devuelve bien si el año es bisiesto
   function esBisiesto(nAno){
    var bRes = true;
    res = bRes && (nAno % 4 == 0);
    res = bRes && (nAno % 100 != 0);
    res = bRes || (nAno % 400 == 0);
    return bRes;
   }*/

   /* Esta si funciona bien */
   
function esBisiesto(nAno) {
        return (((
nAno % 4 == 0) && (nAno % 100 != 0)) || (nAno % 400 == 0)) ? true : false; 
} 


   function 
finMes(nMes, nAno){
    var 
nRes = 0;
    switch (
nMes){
     case 
1: nRes = 31; break;
     case 
2: nRes = 28; break;
     case 
3: nRes = 31; break;
     case 
4: nRes = 30; break;
     case 
5: nRes = 31; break;
     case 
6: nRes = 30; break;
     case 
7: nRes = 31; break;
     case 
8: nRes = 31; break;
     case 
9: nRes = 30; break;
     case 
10: nRes = 31; break;
     case 
11: nRes = 30; break;
     case 
12: nRes = 31; break;
    }
    return 
nRes + (((nMes == 2) && esBisiesto(nAno))? 1: 0);
   }

   function 
diasDelAno(nAno){
    var 
nRes = 365;
    if (
esBisiesto(nAno)) nRes++;
    return 
nRes;
   }

   function 
anosEntre(nDi0, nMe0, nAn0, nDi1, nMe1, nAn1){
    var 
nRes = Math.max(0, nAn1 - nAn0 - 1);
    if (
nAn1 != nAn0)
     if ((
nMe1 > nMe0) || ((nMe1 == nMe0) && (nDi1 >= nDi0)))
      
nRes++;
    return 
nRes;
   }

   function 
mesesEntre(nDi0, nMe0, nAn0, nDi1, nMe1, nAn1){
    var 
nRes;
    if ((
nMe1 < nMe0) || ((nMe1 == nMe0) && (nDi1 < nDi0))) nMe1 += 12;
    
nRes = Math.max(0, nMe1 - nMe0 - 1);
    if ((
nDi1 > nDi0) && (nMe1 != nMe0)) nRes++;
    return 
nRes;
   }

   
/* Tiene un error en 2 fechas con el mismo dia, devolvía 0 dias al pasarle
   dos fechas del mismo dia pero la fecha fin con al mes siguiente que la fecha
   de inicio.
   Ejemplo de bug:
          fecha_inicio: 15/03/2008
          fecha_fin:     15/04/2008
   */
   /*function diasEntre(nDi0, nMe0, nAn0, nDi1, nMe1, nAn1){
    var nRes;
    if (nDi1 < nDi0) nDi1 += finMes(nMe0, nAn0);
    nRes = Math.max(0, nDi1 - nDi0);
    return nRes;
   }*/

   /* Funcion correcta */
   
function diasEntre(nDi0, nMe0, nAn0, nDi1, nMe1, nAn1) {
       var 
nRes; 
       if(
nMe0 != nMe1) {
               
nDi1 += finMes(nMe0, nAn0);
       }        
       
nRes = Math.max(0, nDi1 - nDi0); 
       return 
nRes; 
   }

   function 
mayorOIgual(nDi0, nMe0, nAn0, nDi1, nMe1, nAn1){
    var 
bRes = false;
    
bRes = bRes || (nAn1 > nAn0);
    
bRes = bRes || ((nAn1 == nAn0) && (nMe1 > nMe0));
    
bRes = bRes || ((nAn1 == nAn0) && (nMe1 == nMe0) && (nDi1 >= nDi0));
    return 
bRes;
   }

   function 
calcula(){
    var 
sFc0 = document.frm.fecha0.value; // Se asume válida
    
var sFc1 = document.frm.fecha1.value; // Se asume válida
    
var nDi0 = parseInt(sFc0.substr(0, 2), 10);
    var 
nMe0 = parseInt(sFc0.substr(3, 2), 10);
    var 
nAn0 = parseInt(sFc0.substr(6, 4), 10);
    var 
nDi1 = parseInt(sFc1.substr(0, 2), 10);
    var 
nMe1 = parseInt(sFc1.substr(3, 2), 10);
    var 
nAn1 = parseInt(sFc1.substr(6, 4), 10);
    if (
mayorOIgual(nDi0, nMe0, nAn0, nDi1, nMe1, nAn1)){
     var 
nAno = anosEntre(nDi0, nMe0, nAn0, nDi1, nMe1, nAn1);
     var 
nMes = mesesEntre(nDi0, nMe0, nAn0, nDi1, nMe1, nAn1);
     var 
nDia = diasEntre(nDi0, nMe0, nAn0, nDi1, nMe1, nAn1);
     var 
nTtM = nAno * 12 + nMes;
     var 
nTtD = nDia;
     for (var 
i = nAn0; i < nAn0 + nAno; i++) nTtD += diasDelAno(nAno);
     for (var 
j = nMe0; j < nMe0 + nMes; j++) nTtD += finMes(j, nAn1);
     var 
nTSS = Math.floor(nTtD / 7);
     var 
nTSD = nTtD % 7;
     
document.frm.difDMA.value = String(nAno) + " años, " + String(nMes) + " meses, " + String(nDia) + " días";
     
document.frm.difDM.value = String(nTtM) + " meses, " + String(nDia) + " días";
     
document.frm.difD.value = String(nTtD) + " días";
     
document.frm.difSD.value = String(nTSS) + " semanas, " + String(nTSD) + " días";
    } else 
alert("Error en rango");
   }
  
</script>
 </head>
 <body>
  <form name="frm">
   <table border="0">
    <tr>
     <td>
      <table border="1">
       <tr>
        <td align="right">
         Fecha inicial (dd/mm/aaaa)
        </td>
        <td>
         <input type="text" name="fecha0" value="31/08/1996">
        </td>
       </tr>
       <tr>
        <td align="right">
         Fecha final (dd/mm/aaaa)
        </td>
        <td>
         <input type="text" name="fecha1" value="09/07/1999">
        </td>
       </tr>
       <tr>
        <td align="right">
         Diferencia (D,M,A)
        </td>
        <td>
         <input type="text" name="difDMA" readonly>
        </td>
       </tr>
       <tr>
        <td align="right">
         Diferencia (D,M)
        </td>
        <td>
         <input type="text" name="difDM" readonly>
        </td>
       </tr>
       <tr>
        <td align="right">
         Diferencia (D)
        </td>
        <td>
         <input type="text" name="difD" readonly>
        </td>
       </tr>
       <tr>
        <td align="right">
         Diferencia (SD)
        </td>
        <td>
         <input type="text" name="difSD" readonly>
        </td>
       </tr>
      </table>
     </td>
    </tr>
    <tr>
     <td align="center">
      <input type="button" value="Calcular" onclick="calcula()">
     </td>
    </tr>
   </table>
  </form>
 </body>
</html> 

[/QUOTE]

caricatos 01/04/2008 01:14

FAQ124 - Adjuntar varios ficheros
 
P: ¿Como puedo adjuntar varios ficheros dinámicamente?

R: Seguro que ya habrá algún mensaje para añadir campos dinámicamente, pero en ocasiones son de difícil validación por el atributo name de los mismos (en explorer no conozco modo de referenciar por ese atributo los campos creados dinámicamente)

El tema se desarrolló en el mensaje: añadir name="userfile[]" a script de http://the-stickman.com/ de upload multiple file, y el código final sería:

Código:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>
        http://www.caricatos.net/probador
</title>
<script>
function tag(id) {return document.getElementById(id)};
var actual = total = 0;
var maximo = 5;
function listar(f)        {
        if (actual == total)        {
                actual = ++total;
                nuevo = document.createElement("div");
                nuevo.onclick = function() {
                        tag("file_" + actual).style.display = "none";
                        tag("elemento_" + actual).style.backgroundColor = "white";
                        actual = this.id.substr(9);
                        tag("file_" + actual).style.display = "inline";
                        tag("elemento_" + actual).style.backgroundColor = "#eeeeee";
                }
                nuevo.id = "elemento_" + (actual - 1);
                tag("listado").appendChild(nuevo);
                nuevo.appendChild(document.createTextNode(f.value));
                nuevo.style.cursor = "pointer";
                if (total < maximo)        {
                        nuevof = f.cloneNode(true);
                        f.style.display = "none";
                        nuevof['value'] = "";
                        nuevof.id = "file_" + actual;
                        f.parentNode.insertBefore(nuevof, f.nextSibling);
                }
                else        {
                        tag("oculto").style.display = "none";
                        actual = 4;
                        tag("elemento_" + actual).style.backgroundColor = "#eeeeee";
                }
        }
        else        {
                elem = tag("elemento_" + actual);
                elem.replaceChild(document.createTextNode(f.value), elem.firstChild);
                //tag("elemento_" + actual).innerHTML = f.value;
        }
}
</script>
</head>

<body>
        <form action="javascript: alert('Ok')" >
                <input type="file" onchange="listar(this)" name="userfile[]" id="file_0" size="50" />
                <button type="submit"> enviar </button>
        </form>
        <div id="listado" style="position: relative; background-color: white">
                <div id="oculto" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-color: transparent">
                </div>
        </div>
</body>
</html>

Se ha añadido un sistema de selección mejorado (con resalte y cursor "pointer")

Saludos :arriba:

drkcid 11/04/2008 04:17

Re: FAQs JavaScript
 
P:¿Como puedo validar la direccion de un archivo?

R: Después de mucho busvar y no encontrar una expresión regular para este problema he llegado a la siguiente conclusion:

Cita:

function validaTexto(texto)
{
var
re = /^[-_:\w\.\/\\]+$/i;
if (
!re.test(texto.value)) {
alert (
"Direccion no valida.");
return
false;
}
return
true;
}

Esto valida que la direeción del archivo sea valida (pEj: c:\imagenes\miimagen.jpg) y además no permite que el nombre del archivo tenga caracteres extraños, espacios o acentos que siempre pueden dar problemas.
Tambien sirve para URL.
Puedes usarlo en un formulario como este:
Cita:

<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
<table width="100%">
<tr>
<td>Insertar Imagen</td>
<td><label>
<input name="imagenes" type="file" id="imagenes" size="60" onblur="validaTexto(this)" />
</label>
</td>
</tr>
<tr>
<td><input type="submit" name="addImg" id="addImg" value="Enviar" /></td>
</tr>
</table>
</form>

MaBoRaK 20/06/2008 10:53

Respuesta: FAQs JavaScript
 
loading.............


P: Como crear variables globales dentro de una funcion
R: Así

Código PHP:

function(){
      
window['mivariableglobal']=23423423432;
} 

connection closed.

MaBoRaK 20/06/2008 10:57

Respuesta: FAQs JavaScript
 
loading.........


P: Internet Explorer y otros browsers no tiene XMLSerializer
R: A crearlo

Código PHP:

if((typeof XMLSerializer)==='undefined')
                {
                    
window.XMLSerializer = function() {
                        
this.toString=function()
                        {
                            return 
"[object XMLSerializer]";
                        };
                        
this.serializeToString=function(xml){
                            return 
xml.xml || xml.outerHTML || "Error XMLSerializer";
                        };
                    };    
                } 

Muy importante poner

window.XMLSerializer = function()

y no asi
function XMLSerializer()



connection closed.

Panino5001 24/06/2008 13:36

Respuesta: FAQs JavaScript
 
P: Cómo ajustar el tamaño de un iframe a las dimensiones de la página que contiene:
R:
Código PHP:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<
html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<
title></title>
<
script>
function 
getWindowData(n,i){
    var 
ifr=document.getElementById(i).contentWindow.document || document.getElementById(i).contentDocument;
    var 
widthViewport,heightViewport,xScroll,yScroll,widthTotal,heightTotal;
    if (
typeof window.frames[n].innerWidth != 'undefined'){
        
widthViewport= window.frames[n].innerWidth;
        
heightViewport= window.frames[n].innerHeight;
    }else if(
typeof ifr.documentElement != 'undefined' && typeof ifr.documentElement.clientWidth !='undefined' && ifr.documentElement.clientWidth != 0){
        
widthViewport=ifr.documentElement.clientWidth;
        
heightViewport=ifr.documentElement.clientHeight;
    }else{
        
widthViewport= ifr.getElementsByTagName('body')[0].clientWidth;
        
heightViewport=ifr.getElementsByTagName('body')[0].clientHeight;
    }
    
xScroll=window.frames[n].pageXOffset || (ifr.documentElement.scrollLeft+ifr.body.scrollLeft);
    
yScroll=window.frames[n].pageYOffset || (ifr.documentElement.scrollTop+ifr.body.scrollTop);
    
widthTotal=Math.max(ifr.documentElement.scrollWidth,ifr.body.scrollWidth,widthViewport);
    
heightTotal=Math.max(ifr.documentElement.scrollHeight,ifr.body.scrollHeight,heightViewport);
    return [
widthViewport,heightViewport,xScroll,yScroll,widthTotal,heightTotal];
} 
function 
resizeIframe(ID,NOMBRE){
document.getElementById(ID).height=null;
document.getElementById(ID).width=null;
window.location='#';//necesario para safari
var m=getWindowData(NOMBRE,ID); 
document.getElementById(ID).height=m[5];
document.getElementById(ID).width=m[4]+22;
} 
function 
addEvent(obj, evType, fn, useCapture){
 
 if (
obj.addEventListener){
    
obj.addEventListener(evType, fn, useCapture);
    
  } else if (
obj.attachEvent){
    
obj.attachEvent("on"+evType, fn);
   
  } else {
   
obj['on'+evType]=fn;
  }
}
window.onload=function(){
    
resizeIframe('pp','pp');
    
addEvent(document.getElementById('pp'), 'load', function(){resizeIframe('pp','pp');}, false);
}
</script>
</head>

<body>
<iframe name="pp" id="pp" src="test2.php" frameborder="1" scrolling="no"></iframe></body>
</html> 

(Probado en Safari, Explorer, Ópera y Firefox)

Panino5001 24/06/2008 13:47

Respuesta: FAQs JavaScript
 
P: cómo crear un editor WISYWYG sencillo:
R:
Código PHP:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<
html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<
title></title>
<
style>
input{
border:1px solid #000;
background:#CCCCCC;
font-family:Verdana, Arial, Helvetica, sans-serif;
font-size:9px;
margin-bottom:3px;
}
</
style>
<
script>
var 
editor;
function $(
id){
    return 
document.getElementById(id);
}
function 
formato(f){
    
editor.execCommand(f, false, null);
}
function 
rev(t)    {
    return 
t.split("<").join("&lt;").split(">").join("&gt;").split("\"").join("&quot;");
}
function 
insertarEnlace(){
    var 
u;
    if(!(
u=prompt('ingresar url','http://')))return;
    
editor.execCommand("CreateLink",false,u);
}
function 
insertarImagen(){
    var 
u;
    if(!(
u=prompt('ingresar url','http://')))return;
    
editor.execCommand("InsertImage",false,u);
}
function 
color(c){
    
editor.execCommand("forecolor",false,c);
}

function 
colorFondo(c){
    var 
h=window.ActiveXObject?'backcolor':'hilitecolor';
    
editor.execCommand(h,false,c);
}
function 
inHTML(){
    var 
u,u2;
    if(!(
u=prompt('ingresar html')))return;
    
        try{
            
editor.execCommand("inserthtml",false,u);
        }catch(
e){
            try{
                
u2=editor.selection.createRange();
                
u2.pasteHTML(u);
            }catch(
E){
                
alert('nop');
            }
        }
}

function 
htmlOEditor(e){
e=e || window.event;
ob=e.target || e.srcElement
$('edit').style.display=(ob.value=='html')?'none':'block';
$(
'ht').style.display=(ob.value!='html')?'none':'block';
$(
'ht').innerHTML=rev(editor.body.innerHTML);
ob.value=(ob.value=='html')?'editor':'html';
}
window.onload=function(){
    
    
editor=$('edit').contentDocument || $('edit').contentWindow.document;
    
editor.designMode='on';
}
</script>
</head>

<body>
<form id="form1" name="form1" method="post" action="">
  <input type="button" name="Submit" value="N" onclick="formato('bold')" />
  <input type="button" name="Submit2" value="C" onclick="formato('italic')" />
  <input type="button" name="Submit3" value="S" onclick="formato('underline')" />
  <input type="button" name="Submit4" value="remover formato" onclick="formato('RemoveFormat')" />
  <input type="button" name="Submit5" value="link" onclick="insertarEnlace()" />
  <input type="button" name="Submit9" value="quitar link" onclick="formato('Unlink')" />
  <input type="button" name="Submit6" value="imagen" onclick="insertarImagen()" />
  <input type="button" name="Submit7" value="texto rojo" onclick="color('#FF0000')" />
  <input type="button" name="Submit8" value="fondo rojo" onclick="colorFondo('#FF0000')" />
    <input type="button" name="Submit10" value="deshacer" onclick="formato('undo')" />
  <input type="button" name="Submit11" value="rehacer" onclick="formato('redo')" />

  <input type="button" name="Submit12" value="insertar html" onclick="inHTML()" />
  <br />
<iframe id="edit" width="100%" height="300" style=" border:1px solid #000;"></iframe>
<div id="ht" style="width:100%; height:300px; overflow:auto; border:1px solid #000; display:none"></div>
<div style="margin-top:3px;"><input name="ver" type="button" id="ver" onclick="htmlOEditor(event)" value="html" /></div>
</form>
</body>
</html> 

(Probado en Safari, Explorer, Ópera y Firefox)

Adler 30/06/2008 14:52

Respuesta: Validar E-Mail
 
Código PHP:

function vMail(ce) {
var 
okem= ce.email.value;

var 
localOK = /^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$/;
var ipOK = /^[?[0-9.]+]?$/;
var 
dominoOK = /^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$/;

// El email consta de dos partes dividas por @
var email_array = okem.split('@');

if (
email_array.length < 2 || email_array.length > 2) {
alert("La dirección de email 1  ("+ email_array.length +") no es válida.");
       
document.forms.sendmail.email.focus();
       return (
false);
    }

// Incorrecto número de caracteres en alguna de las dos partes
if (email_array[0].length  < 1 || email_array[1].length  < 1) {
alert("La dirección de email 2 ("+ email_array[0].length +") -- ("+ email_array[1].length +") no es válida.");
       
document.forms.sendmail.email.focus();
       return (
false);
    }

var 
local_array = email_array[0].split('.');
for (
i = 0; i < local_array.length; i++)
{
if (!
localOK.test(local_array[i])) {
alert("La dirección de email 3 ("+ local_array[i] +") no es válida.");
       
document.forms.sendmail.email.focus();
       return (
false);
    }
}

// Se revisa si el dominio es una IP. Si no, debe ser un nombre de dominio válido
if (!ipOK.test(okem)) {

var 
dominio_array = email_array[1].split('.');
// Incorrecto número de secciones por exceso o defecto para ser un dominio
if (dominio_array.length < 2 || dominio_array.length > 3) {
alert("La dirección de email 4 ("+ dominio_array.length +") no es válida.");
       
document.forms.sendmail.email.focus();
       return (
false);
    }

for (
i = 0; i < dominio_array.length; i++)
{
if (!
dominoOK.test(dominio_array[i])) {
alert("La dirección de email 5 ("+ dominio_array[i] +") no es válida.");
       
document.forms.sendmail.email.focus();
       return (
false);
    }
        }
}
else
return (
true)
} 

Mismo código en php

Mismo código en asp

andrewp 27/07/2008 01:57

Respuesta: FAQs JavaScript
 
Pregunta: Cómo puedo validar un grupo de radio buttons?
Respuesta: Respuesta complementada por XBX:

En el header deberías incluir el siguiente código:

Código PHP:

<script language="javascript">
function 
query_validator(){
    var 
isOneChecked = false;
    for (var 
i=0; i < document.form.grupo.length; i++)
    {
         if(
document.form.grupo[i].checked){
            
isOneChecked = true;
            break;
         }
    }

    if (!
isOneChecked) {
        
alert('Por favor, seleccione una respuesta');
         return(
false);
    }
}
</script> 

En el body de tu página debes inclmuír la siguiente acción en el inicio del formulario:

Código PHP:

<form name="form3" action="respuestas.php" method="post" onsubmit="return query_validator();">
... 
Aqui el resto de tu codigo con el grupo de radio buttons incluido ...
</
form> 


marcopoloaz06 05/08/2008 11:39

274.- PUNTEROS en un Array
 
P:¿ Cómo usar las funciones de PHP current(),next(),prev(),end(),reset(), en JavaScript ?
R: [EJEMPLO]

asi:
Código HTML:

<script type="text/javascript">
(function(){
// PUNTEROS ARRAY
Array.prototype.currentNum = 0;
Array.prototype.current = function(){
    return this[ this.currentNum ];
};
Array.prototype.next = function(){
    return this.currentNum+1<this.length ? this[ ++this.currentNum ] : false;
};
Array.prototype.prev = function(){
    return this.currentNum-1>
0 ? this[ --this.currentNum ] : false;
};
Array.prototype.end = function(){
    return this.length>0 ? this[ this.currentNum = this.length-1 ] : false;
};
Array.prototype.reset = function(){
    return this[ this.currentNum = 0 ];
};
})();
</script>

pueden ver el ejemplo

Saludos
:]

marcopoloaz06 13/08/2008 22:58

275.- ¿Cómo hacer un Enum?
 
P:¿Cómo hacer un Enum como en otros lenguajes de programación?
R: asi:

Código PHP:

    function Enum(nombRe, valoRes){
        
window[nombRe] = {};
        for(var 
i=j=0;i<valoRes.length;i++,j++){
            var 
s = valoRes[i].split("-");
            
window[nombRe][( s.length>1 ) ? s[0] : valoRes[i] ] = ( s.length>1 ) ? j=Number( s[1] ) : j;
        }
    };
    
Enum.isDefined = function( Enum, val ){
        for( 
x in Enum ){
            if( 
x==val ) return Enum[x];
        }
        return -
1;
    };
    
// EJEMPLOS
    
Enum( "maRco", ["a", "as", "asd", "asdf", "asdfg", "asdfgh"] );
     
maRco = {a: 0, as: 1, asd: 2, asdf: 3, asdfg: 4, asdfgh: 5};
    
Enum( "pOlo", ["z-1", "y", "x"] )
     
pOlo = {z: 1, y: 2, x: 3};
    
Enum( "aZ", ["x-1", "xd", "xD-10", "XD", "Xd-20", "d"] );
     
aZ = {x: 1, xd: 2, xD: 10, XD: 11, Xd: 20, d:21};
    
Enum.isDefined( aZ, "XD" );
     
// return 11; 

Saludos &
adios...
;]

Panino5001 07/09/2008 15:53

Respuesta: FAQs JavaScript
 
P: Cómo logar un efecto espejo con javascript?
R: Usando Canvas para los navegadores estandar y un filtro propietario para explorer. Ejemplo . Código del ejemplo
Código PHP:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<
html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<
title>test</title>
<
script>
function 
reflejo (contenedor, imagen) {
        var 
ref = false;
        if (
document.createElement("canvas").getContext) {
            
/* ---- canvas ---- */
            
ref = document.createElement("canvas");
            
ref.width = imagen.width;
            
ref.height = imagen.height;
            var 
context = ref.getContext("2d");
            
context.translate(0, imagen.height);
            
context.scale(1,-1);
            
context.drawImage(imagen, 0, 0, imagen.width, imagen.height);
            
ref.style.opacity = '0.35';
        } else {
            
/* ---- DXImageTransform ---- */
            
ref=document.createElement('img');
            
ref.src=imagen.src;
            
ref.style.filter = 'flipv progid:DXImageTransform.Microsoft.Alpha(opacity=50, style=1, finishOpacity=0, startx=0, starty=0, finishx=0, finishy=' + imagen.height + ')';
        
ref.width= imagen.width;
        
ref.height= imagen.height;
        }
        
ref.style.position = 'absolute';
        
ref.style.left= 0;
        
ref.style.top= imagen.height+'px'
        
contenedor.appendChild(ref);
    }
window.onload=function(){
    
reflejo(document.getElementById('pp'), document.getElementById('ll'));
}
</script>
</head>

<body>
<div id="pp" style="position:relative"><img id="ll" src="5.jpg" width="180" height="144" /></div>
</body>
</html> 

Si bien el efecto está bastante logrado, podemos mejorarlo haciendo que el resultado en navegadores estandar se parezca más al que obtenemos en Explorer, aplicando gradientes como hace este último en su filtro. Este sería el resultado final.
Y este el código utilizado:
Código PHP:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<
html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<
title>test</title>
<
script>
function 
reflejo (contenedor, imagen) {
        var 
ref = false;
        if (
document.createElement("canvas").getContext) {
            
/* ---- canvas ---- */
            
ref = document.createElement("canvas");
            
ref.width = imagen.width;
            
ref.height = imagen.height;
            var 
context = ref.getContext("2d");
            
context.translate(0, imagen.height);
            
context.scale(1,-1);
            
context.drawImage(imagen, 0, 0, imagen.width, imagen.height);
            
context.globalCompositeOperation = "destination-out";
            var 
gradient = context.createLinearGradient(0, 0, 0, imagen.height);
            
gradient.addColorStop(0, "rgba(255, 255, 255, 1.0)");
            
gradient.addColorStop(1, "rgba(255, 255, 255, 0.1)");
            
context.fillStyle = gradient;
            
context.fillRect(0,0,imagen.width, imagen.height);
        } else {
            
/* ---- DXImageTransform ---- */
            
ref=document.createElement('img');
            
ref.src=imagen.src;
            
ref.style.filter = 'flipv progid:DXImageTransform.Microsoft.Alpha(opacity=50, style=1, finishOpacity=0, startx=0, starty=0, finishx=0, finishy=' + imagen.height + ')';
        
ref.width= imagen.width;
        
ref.height= imagen.height;
        }
        
ref.style.position = 'absolute';
        
ref.style.left= 0;
        
ref.style.top= imagen.height+'px'
        
contenedor.appendChild(ref);
    }
window.onload=function(){
    
reflejo(document.getElementById('pp'), document.getElementById('ll'));
}
</script>
</head>

<body>
<div id="pp" style="position:relative"><img id="ll" src="5.jpg" width="180" height="144" /></div>
</body>
</html> 

(Probado en Explorer, Safari, Ópera, Firefox y Chrome)

Panino5001 07/09/2008 16:02

Respuesta: FAQs JavaScript
 
P: Se puede rotar una imagen usando javascript?
R: Sí, y más allá del camino chapucero que propuse en este post, la inclusión de soporte para el elemento html estandar llamado canvas en la mayoría de los navegadores modernos, junto a filtros propietarios del único navegador popular que no soporta dicho elemento, nos permiten tranquilamente realizar esta tarea. Ejemplo. Código del ejemplo:
Código PHP:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<
html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<
title>test</title>
<
script>
function 
rotar(obj,angulo){
    if (
angulo >= 0) {
        var 
rotation = Math.PI * angulo / 180;
    } else {
        var 
rotation = Math.PI * (360+angulo) / 180;
    }
    var 
costheta = Math.cos(rotation);
    var 
sintheta = Math.sin(rotation);
    if (
document.createElement("canvas").getContext) {
    
/* ---- canvas ---- */ 
        
var c=document.createElement('canvas');
        
c.width = Math.abs(costheta*obj.width) + Math.abs(sintheta*obj.height);
        
c.style.width = c.width+'px';
        
c.height = Math.abs(costheta*obj.height) + Math.abs(sintheta*obj.width);
        
c.style.height=c.height+'px';
        
c.id=obj.id;
        
c.style.position='absolute';
        var 
ctx=c.getContext('2d');
        
ctx.save();
        if (
rotation <= Math.PI/2) {
            
ctx.translate(sintheta*obj.height,0);
        } else if (
rotation <= Math.PI) {
            
ctx.translate(c.width,-costheta*obj.height);
        } else if (
rotation <= 1.5*Math.PI) {
            
ctx.translate(-costheta*obj.width,c.height);
        } else {
            
ctx.translate(0,-sintheta*obj.width);
        }
        
ctx.rotate(rotation);
        
ctx.drawImage(obj, 0, 0, obj.width, obj.height);
        
obj.parentNode.replaceChild(c,obj);
        
ctx.restore();
    }else{
    
/* ---- DXImageTransform ---- */
        
obj.style.position='absolute';
        
obj.style.filter="progid:DXImageTransform.Microsoft.Matrix(sizingMethod='auto expand')";
        
obj.filters.item(0).M11 = costheta;
        
obj.filters.item(0).M12 = -sintheta;
        
obj.filters.item(0).M21 = sintheta;
        
obj.filters.item(0).M22 = costheta;
    }
}
window.onload=function(){
    
rotar(document.getElementById('pp'),60);
    
}
</script>
</head>

<body>
<img src="1.jpg" width="180" height="127" />
<div id="ll" style="position:relative; "><img id="pp" src="1.jpg" width="180" height="127" /></div>
</body>
</html> 

(Ejemplo probado en Explorer, Safari, Ópera, Firefox y Chrome)

Raya2 07/10/2008 17:19

Respuesta: FAQs JavaScript
 
P: SOLO PARA CHILE - Validacion del RUT
R: Script siguiente
Lo unico a tener en cuenta es que el RUT debe ingresarse en el formato:
12345678-9
Código del ejemplo:
Código PHP:

function validaRut(rut){
    var 
rutlimpio = "";
    for (
i=0; i < rut.length; i++){
        if ((
rut.charAt(i)!=".") && (rut.charAt(i)!="-"))
            
rutlimpio= rutlimpio + rut.charAt(i);
    }
    
rut=rutlimpio;
    var 
drut=rut.charAt((rut.length-1));
     var 
dvr='0';
    
suma=0;
    
mul=2;
    for (
i=rut.length -2 ; i >= 0; i--){
         
suma=suma + rut.charAt(i) * mul
         
if (mul==7){
             
mul=2;
        }else{
             
mul++;
        }
     }
    
res = suma &#37; 11;
    
if (res==1){
        
dvr = 'k';
    }else if (
res==0){
        
dvr = '0';
    }else{
         
dvi = 11-res;
         
dvr = dvi + "";
     }
    if ((
dvr != drut.toLowerCase())){
         return 
false;
     }else{
        return 
true;
    }
} 

(Ejemplo probado en Explorer y Firefox )

Distriker 25/02/2009 11:42

278. Crear un Pop-Up y variantes ScrollBar y MenuBar
 
P: ¿Cómo crear un Pop-Up e incluirle la barra de desplazamiento y la barra de estado?
R: Solamente deberías de seguir esto:

El codigo del Pop-Up es el siguiente:
Código:
Código javascript:
Ver original
  1. <script>
  2. window.open("http://forosdelweb.com","","width=550,height=420")
  3. </script>

Pruebalo
Recordatorio: Desactivar "Bloquear ventana emergente".

Los scripts hay que ponerlos entre las etiquetas <script></script>, recuerden esto para siempre ;-).

En el Pop-Up (ventana secundaria) puede tener varias variaciones. Una puede ser la de ponerle la barra de desplazamiento:

Ahora viene la pregunta, ¿Como se colocan esas barras de desplazamiento? Muy sencillo. Solo teneis que añadir despues de height y separando con una coma:

Código:
Código:

scrollbars=yes
o
scrollbars=1

Información: 1= Si - 0= No

Entonces, quedaría así:

Código:
Código javascript:
Ver original
  1. <script>
  2. window.open("http://forosdelweb.com","","width=550,height=420,scrollbars=yes")
  3. </script>
o así:
Código javascript:
Ver original
  1. <script>
  2. window.open("http://forosdelweb.com","","width=550,height=420,scrollbars=1")
  3. </script>

Pruebalo.
Recordatorio: Desactivar "ventana emergente".

También le podeis agregar la barra de estado, solamente añadiendo esto:

Código:
Código:

menubar=yes
o
Código:

menubar=1
Recuerden, si quereis que no tenga el menubar, no hace falta que se lo pongais ;-).

Quedaría así:

Código:
Código javascript:
Ver original
  1. <script>
  2. window.open("http://forosdelweb.com","","width=550,height=420,menubar=yes,scrollbars=yes")
  3. </script>

Pruebalo.
Recordatorio: Desactivar "ventana emergente".

¿Qué os parece? ¿Os ha gustado? ¿Os ha servido? ¿Alguna duda? Si es así, preguntadla.

En realidad, un Pop-Up suele ser una ventana sin nada o con el minimo, pero ustedes pueden buscar mas atributos que se le puedan atribuir a este sencillo codigo, venga, animense ;-).

Espero que os haiga gustado.

Puede que mas adelante publique mas de mis cosillas ;-).

Saludos

Creditos: Distriker

venkman 03/03/2009 12:50

Respuesta: FAQs JavaScript
 
Obtener el texto seleccionado.

Código html:
Ver original
  1.     <head>
  2.     <script type="text/javascript">
  3. function getTextoSeleccionado() {
  4.     if (window.getSelection) {
  5.         return window.getSelection();
  6.     } else if (document.getSelection) {
  7.         return document.getSelection();
  8.     } else if (document.selection) {
  9.         return document.selection.createRange().text;
  10.     } else return "Opción no soportada por el navegador";
  11. }
  12.     </script>
  13.  </head>
  14.  <body>
  15.   <form name="frm">
  16.    <table border="0">
  17.     <tr>
  18.      <td align="right">
  19.       input:
  20.      </td>
  21.      <td>
  22.       <input type="textInput" name="txt">
  23.      </td>
  24.     </tr>
  25.     <tr>
  26.      <td align="right">
  27.       textarea:
  28.      </td>
  29.      <td>
  30.       <textarea name="txtArea"></textarea>
  31.      </td>
  32.     </tr>
  33.     <tr>
  34.      <td align="right">
  35.       Link:
  36.      </td>
  37.      <td>
  38.       <a href="#">Enlace</a>
  39.      </td>
  40.     </tr>
  41.     <tr>
  42.      <td align="right">
  43.       Select:
  44.      </td>
  45.      <td>
  46.       <select>
  47.        <option>Uno</option>
  48.        <option>Dos</option>
  49.        <option>Tres</option>
  50.       </select>
  51.      </td>
  52.     </tr>
  53.     <tr>
  54.      <td align="right">
  55.       Párrafo:
  56.      </td>
  57.      <td>
  58.       Esto es un párrafo de donde también se puede seleccionar texto.
  59.      </td>
  60.     </tr>
  61.     <tr>
  62.      <td align="center" colspan="2">
  63.       <a href=javascript:void(alert(getTextoSeleccionado()))>Ver texto seleccionado</a>
  64.      </td>
  65.     </tr>
  66.   </form>
  67.  </body>
  68. </html>

En diferentes navegadores la selección de texto se maneja de forma diferente.


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

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