Foros del Web » Programando para Internet » Javascript »

codigo pho en javascript

Estas en el tema de codigo pho en javascript en el foro de Javascript en Foros del Web. Hola nose muy bien en que foro va mi duda espero que en este, mi problema es que necesito meter codigo php en un archivo ...
  #1 (permalink)  
Antiguo 24/12/2011, 06:34
 
Fecha de Ingreso: noviembre-2011
Mensajes: 516
Antigüedad: 12 años, 5 meses
Puntos: 10
codigo pho en javascript

Hola
nose muy bien en que foro va mi duda espero que en este, mi problema es que necesito meter codigo php en un archivo js y nose si se puede y si se puede como se debe de hacer? gracias un saludo.
  #2 (permalink)  
Antiguo 24/12/2011, 09:23
Avatar de dggluz  
Fecha de Ingreso: abril-2009
Ubicación: Buenos Aires, Argentina
Mensajes: 525
Antigüedad: 15 años
Puntos: 50
Respuesta: codigo pho en javascript

No se puede. ¿Qué deseas hacer? Probablemente debas usar AJAX. ¡Suerte!
  #3 (permalink)  
Antiguo 24/12/2011, 11:34
Avatar de zerokilled
Javascripter
 
Fecha de Ingreso: abril-2009
Ubicación: Isla del Encanto, La Borinqueña [+>==]
Mensajes: 8.050
Antigüedad: 15 años
Puntos: 1485
Respuesta: codigo pho en javascript

buenas,
se puede poner código php en un *.js, o técnicamente cualquier tipo de archivo. ahora bien, recuerda que el navegador no interpreta php, sino sería más fácil para vulnerar un sitio web. para hacerlo funcionar en diferentes archivos tienes que configurar el servidor adecuadamente. por ejemplo en apache tienes que agregar esto, AddType application/x-httpd-php .js. sin embargo, tiene unas consecuencias. el servidor siempre le pedirá a php que analice el documento antes de enviarlo al cliente, incluso aunque no tenga código php. tengo entendido que degrada sustancialmente el rendimiento dado el proceso que conlleva.

pienso que la mejor alternativa, tanto para no afectar el rendimiento como para el caso en que no puedas configurar el servidor, es crear un documento php común y corriente pero en lugar de devolver código html, devolver código javascript. o sea, generar un documento javascript con php. es tan simple como enviar la cabecera Content-Type: text/javascript al inicio y luego utilizar php donde sea necesario. por supuesto, en el atributo src de <script> debes acomodar la url al documento php.
__________________
la maldad es una virtud humana,
y la espiritualidad es la lucha del hombre contra su maldad.
  #4 (permalink)  
Antiguo 24/12/2011, 13:43
 
Fecha de Ingreso: noviembre-2011
Mensajes: 516
Antigüedad: 12 años, 5 meses
Puntos: 10
Respuesta: codigo pho en javascript

Cita:
Iniciado por dggluz Ver Mensaje
No se puede. ¿Qué deseas hacer? Probablemente debas usar AJAX. ¡Suerte!
Pues quiero hacer una consulta a la base de datos y que me dewelva una foto y unos comentarios segun el id que saque yo pero eso solo se hacerlo con php no se con javascript ni ajax ni nada si me puedes explicar te lo agradecería, un saludo.
  #5 (permalink)  
Antiguo 24/12/2011, 13:50
Avatar de dggluz  
Fecha de Ingreso: abril-2009
Ubicación: Buenos Aires, Argentina
Mensajes: 525
Antigüedad: 15 años
Puntos: 50
Respuesta: codigo pho en javascript

Ok, ¿y por qué no quieres hacerlo con PHP?
  #6 (permalink)  
Antiguo 24/12/2011, 13:57
 
Fecha de Ingreso: noviembre-2011
Mensajes: 516
Antigüedad: 12 años, 5 meses
Puntos: 10
Respuesta: codigo pho en javascript

como ya e dixo antes no se si se puede hacer con otro lenguaje ni se de otro lenguaje yo en javascritp se hacer funciones como y con que lenguaje podria hacer una consulta a la base de datos??? gracias.
  #7 (permalink)  
Antiguo 24/12/2011, 14:21
Avatar de dggluz  
Fecha de Ingreso: abril-2009
Ubicación: Buenos Aires, Argentina
Mensajes: 525
Antigüedad: 15 años
Puntos: 50
Respuesta: codigo pho en javascript

Ok, mira... la realidad es más compleja de lo que te estoy contando. Así como te contó zerokilled, puedes insertar código PHP en JavaScript, pero no creo que sea lo que estás preguntando. También puedes programar con JavaScript del lado del servidor (por ejemplo, con NodeJs), y puedes hacer consultas a una base de datos y demás (JavaScript en general se usa del lado del cliente, pero están surgiendo muchos proyectos para usarlo del lado del servidor), pero tampoco creo que sea lo que estás preguntando. En realidad, no termino de entender si quieres satisfacer una curiosidad o resolver un problema. Lenguajes hay muchos y se pueden utilizar para muchas cosas.
Lo que yo esperaba saber es si lo que querías es obtener los resultados de la consulta a una base de datos en el servidor. Si es así, debes resolverlo con PHP (o ASP, o Java o Smalltalk, o JavaScript, o... pero dijiste saber PHP, así que PHP es lo más sencillo). Lo importante es que entiendas que lo debes hacer del lado del servidor. Si además, quieres que esa información la puedas cargar sin necesidad de recargar la página, entonces deberías usar AJAX (que es un elemento que proveen los navegadores y que tiene fundamentalmente una API JavaScript).
Si lo que quieres es aprender AJAX o JavaScript, puedo recomendarte éste sitio.
Pero es muy difícil aconsejarte porque sigo sin saber cuál es en verdad la consulta. ¡Suerte!
  #8 (permalink)  
Antiguo 24/12/2011, 14:52
 
Fecha de Ingreso: noviembre-2011
Mensajes: 516
Antigüedad: 12 años, 5 meses
Puntos: 10
Respuesta: codigo pho en javascript

pues haber yo uso un ejemplo la libreria de lightbox quiero que en esta poder comentar y ver dichos comentarios de la base de datos segun el id de imagenes. entonces la consulta de esa tabla la deberia acer en el jquery.lightbox-0.5.js en un div que cree para eyo mi pregunta es como meter en ese codigo js una consulta que me saque los datos de la tabla de comentarios??? nose coomo puedo hacerlo ni con que lenguaje ya que dicen q no puedo meter php entonces desconozco como hacerlo? gracias un saludo.
  #9 (permalink)  
Antiguo 24/12/2011, 15:14
Avatar de neb642  
Fecha de Ingreso: noviembre-2010
Ubicación: Argentina
Mensajes: 29
Antigüedad: 13 años, 5 meses
Puntos: 3
Respuesta: codigo pho en javascript

Creo que entiendo lo que deseas hacer. En primer lugar, con php se puede mostrar comentarios de una tabla tranquilamente. Pero tu problema está en que tu código php debería estar en un div, pero ese div es un lightbox que creas, como hace facebook para mostrarte imágenes. Así que tienes dos alternativas:

1) poner la consulta php en un div oculto. Y luego con el lightbox muestras ese div oculto y por ende aparecen los comentarios. Aunque no lo recomiendo ya que si son muchas imagenes, son muchas consultas que se hacen aunque solo veas una imagen en el lightbox. Además de que deberías crear tantos divs ocultos como imágenes hayan en el lightbox.

2) usar Ajax: cuando el lightbox se muestra, automáticamente con javascript haces una petición al servidor en busca de los comentarios. De esta manera solo se hacen las consultas necesarias cuando sea necesario.

Espero te haya entendido. Saludos
  #10 (permalink)  
Antiguo 25/12/2011, 04:31
 
Fecha de Ingreso: noviembre-2011
Mensajes: 516
Antigüedad: 12 años, 5 meses
Puntos: 10
Respuesta: codigo pho en javascript

con ajax se pueden hacer consultas a la base de datos como se haría esque de ajax no se nada de nada, gracias un saludo.
  #11 (permalink)  
Antiguo 25/12/2011, 15:35
Avatar de dggluz  
Fecha de Ingreso: abril-2009
Ubicación: Buenos Aires, Argentina
Mensajes: 525
Antigüedad: 15 años
Puntos: 50
Respuesta: codigo pho en javascript

Con AJAX se pueden hacer consultas al servidor. Puedes hacer una página PHP diseñada para responder esas consultas, y dentro de ésta hacer consultas a la base de datos (no consultarías la base de datos directamente con AJAX, sino mediante un script PHP). En resumen: JavaScript + PHP + AJAX + SQL (suponiendo que trabajas con una BD relacional, como MySQL). No puedo darte un curso de AJAX mediante el foro, pero sí puedo recomendarte este manual. ¡Suerte!
  #12 (permalink)  
Antiguo 26/12/2011, 05:53
 
Fecha de Ingreso: noviembre-2011
Mensajes: 516
Antigüedad: 12 años, 5 meses
Puntos: 10
Respuesta: codigo pho en javascript

Gracias no pretendia que me dieseis un tutorial por aqui pero esa era mi duda que si se acia con ajax o tenia que usar php jeje y mi duda a sido resulesta ahora ya se como buscar como hacerlo, si tengo dudas de alguna cosilla preguntare por aqui gracias, un saludo.
  #13 (permalink)  
Antiguo 26/12/2011, 06:40
 
Fecha de Ingreso: noviembre-2011
Mensajes: 516
Antigüedad: 12 años, 5 meses
Puntos: 10
Respuesta: codigo pho en javascript

Ya vi un codigo que me sirve para hacer lo que quiero pero lo unico que yo uso lightbox y no va por id sino por la direccion de mi imagen, entonces como ago para que esta segun a foto que veo saber el id y lg pasarlo al ajax.js y por fin hacer la consulta de todos los comentarios de esa foto??? es mi nueva duda. gracias.
  #14 (permalink)  
Antiguo 26/12/2011, 09:18
Avatar de dggluz  
Fecha de Ingreso: abril-2009
Ubicación: Buenos Aires, Argentina
Mensajes: 525
Antigüedad: 15 años
Puntos: 50
Respuesta: codigo pho en javascript

Pásale la URL de la imagen, y arréglate en el servidor para averiguar el resto de los datos. O bien, modifica el funcionamiento de LightBox, o métete a ver su API, quizás quienes lo hicieron hayan pensado en casos como el tuyo (no tengo idea, porque nunca utilicé Lightbox). ¡Suerte!
  #15 (permalink)  
Antiguo 26/12/2011, 14:43
 
Fecha de Ingreso: noviembre-2011
Mensajes: 516
Antigüedad: 12 años, 5 meses
Puntos: 10
Respuesta: codigo pho en javascript

como puedo pasar la url desde el lightbox a otro archivo es que nose como hacerlo ya e probado de mil formas y nose como pasarlo seria de js a php y hay hacer la consulta con ajax desde el js otra vez nse como hacerlo. gracias.
  #16 (permalink)  
Antiguo 27/12/2011, 07:09
 
Fecha de Ingreso: noviembre-2011
Mensajes: 516
Antigüedad: 12 años, 5 meses
Puntos: 10
Respuesta: codigo pho en javascript

e creado una variable en js var objeto con lo que kiero que me mande pero nose si esta bien hecho ni como debo recojerlo si por post, server, o como por que al no ser un formulario el que la manda no se si se puede hacer ni como, un saludo. espero que me puedan ayudar.
  #17 (permalink)  
Antiguo 27/12/2011, 09:18
Avatar de dggluz  
Fecha de Ingreso: abril-2009
Ubicación: Buenos Aires, Argentina
Mensajes: 525
Antigüedad: 15 años
Puntos: 50
Respuesta: codigo pho en javascript

No conozco Lightbox (sí Fancybox), así que mucho no te puedo orientar. Pero es probable que tu solución no sea trivial. Muestra tu código, porque sino se me va a hacer muy difícil ayudarte. ¡Suerte!
  #18 (permalink)  
Antiguo 27/12/2011, 14:31
 
Fecha de Ingreso: noviembre-2011
Mensajes: 516
Antigüedad: 12 años, 5 meses
Puntos: 10
Respuesta: codigo pho en javascript

Pues este es mi codigo de lightox y este es el que uso de php
fotos.php
Código PHP:
<? include("header.php"); 

if (!isset(
$_SESSION['logueado_usuario'])) { 
    include (
"login.php");  
echo 
"<a href='registro.php'>Registrarse</a>" ;} 
    else {  
    
$nombre =$_SESSION['logueado_nombre']; 
    
$id_usuario=$_SESSION['logueado_id']; 



?> 
<!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>Dar estilo a un bot&oacute;n input file</title>
<link href="Css/jquery.si.css" rel="stylesheet" type="text/css" />
<script src="http://jqueryjs.googlecode.com/files/jquery-1.3.1.min.js" type="text/javascript"></script>
<script src="Js/jquery.si.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="Css/jquery.lightbox-0.5.css" media="screen" />
<script src="Js/jquery.lightbox-0.5.js" type="text/javascript"></script>
<script src="Js/funciones_img.js" type="text/javascript"></script>
<div class="file"> <script type="text/javascript">
    $(document).ready(function() {
        $("input.file").si();
    });
</script>

<SCRIPT LANGUAGE="javascript"> 
<!-- 
function validar(){ 
alert('aceptar para seguir'); 
document.formulario.submit(); 
//También te puedes referir a ese objeto mediante un arreglo de esta forma 
//document.forms[0].submit(); 

//--> 
</script> 
<style type="text/css">
/* jQuery lightBox plugin - Gallery style */
#gallery {
padding: 10px;
width: 100px;
}
</style>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="foto" onChange="submit(this)" class="file"/>
</form>
</div>
<?php
include("privados/config.php");
$numero rand(1,10000);
$date_default_timezone_set date_default_timezone_set('Europe/Madrid');
$fecha date('d-n-o H:i:s',strtotime('+0hours'));
$nameimagen $_FILES['foto']['name'];
$tmpimagen  $_FILES['foto']['tmp_name'];

//Comprobamos si los campos están vacios...
if($nameimagen =="" or $tmpimagen=="") {
    
} else {
    
//Establecemos el ancho fijo que tendran las miniaturas
    
$ancho 180;//Ancho de la imagen nueva
    
$ori_ancho=500;
    
$foto_nom=($nameimagen);
            
$foto_nom=str_replace(" ","_",$foto_nom);
            
$nombre_foto=$numero.($nameimagen);
    
//Obtenemos informacion acerca del fichero, para conocer su extension
    
$info pathinfo($nameimagen);
    
    
$tamano getimagesize($tmpimagen);
    
print_r($tamano);
    
    
$width  =  $tamano[0];//Ancho de la imagen
    
$height =  $tamano[1];//Alto de la imagen
    
$original "fotos/$nombre_foto";
    
$copia    "fotos/mini/copia_$nombre_foto";
    
    if(
$width $ori_ancho){
    
$alto 500;//Alto de la imagen nueva
        //Comprobamos si la imagen es JPG
        
switch($info['extension']) { 
            case 
'jpg':
            
$viejaimagen2 imagecreatefromjpeg($tmpimagen); 
            
$nuevaimagen2 imagecreatetruecolor($ori_ancho$alto);//Nueva imagen
            
imagecopyresized($nuevaimagen2$viejaimagen2,0,0,0,0,$ori_ancho,$alto,$width,$height);
            
copy($tmpimagen$original);//imagen.jpg
            
imagejpeg($nuevaimagen2,$original);
            break;
            case 
'png':
            
$viejaimagen2 imagecreatefrompng($tmpimagen); 
            
$nuevaimagen2 imagecreatetruecolor($ori_ancho$alto);//Nueva imagen
            
imagecopyresized($nuevaimagen2$viejaimagen2,0,0,0,0,$ori_ancho,$alto,$width,$height);
            
copy($tmpimagen$original);//imagen.jpg
            
imagepng($nuevaimagen2,$original);
            break;
            case 
'gif':
            
$viejaimagen2 imagecreatefromgif($tmpimagen); 
            
$nuevaimagen2 imagecreatetruecolor($ori_ancho$alto);//Nueva imagen
            
imagecopyresized($nuevaimagen2$viejaimagen2,0,0,0,0,$ori_ancho,$alto,$width,$height);
            
copy($tmpimagen$original);//imagen.jpg
            
imagegif($nuevaimagen2,$original);
            break;
            } }
    
    
//Comprobamos el ancho , para ver si supera los 120
    
if($width $ancho) {
        
$alto 135;//Alto de la imagen nueva
        //Comprobamos si la imagen es JPG
        
switch($info['extension']) { 
            case 
'jpg':
            
$viejaimagen imagecreatefromjpeg($tmpimagen); 
            
$nuevaimagen imagecreatetruecolor($ancho$alto);//Nueva imagen
            
imagecopyresized($nuevaimagen$viejaimagen,0,0,0,0,$ancho,$alto,$width,$height);
            
copy($tmpimagen$copia);
            
imagejpeg($nuevaimagen$copia);
            break;
            case 
'png':
            
$viejaimagen imagecreatefrompng($tmpimagen); 
            
$nuevaimagen imagecreatetruecolor($ancho$alto);//Nueva imagen
            
imagecopyresized($nuevaimagen$viejaimagen,0,0,0,0,$ancho,$alto,$width,$height);
            
copy($tmpimagen$copia);//imagen.jpg
            
imagepng($nuevaimagen,$copia);
            break;
            case 
'gif':
            
$viejaimagen imagecreatefromgif($tmpimagen); 
            
$nuevaimagen imagecreatetruecolor($ancho$alto);//Nueva imagen
            
imagecopyresized($nuevaimagen$viejaimagen,0,0,0,0,$ancho,$alto,$width,$height);
            
copy($tmpimagen$copia);//imagen.jpg
            
imagegif($nuevaimagen,$copia);
            break;
            }
            
            
            
//copia_imagen.jpg
            
            
$nombre_comple="http://redsocial.net63.net/$original";
            
$mini_comple="http://redsocial.net63.net/$copia";
            echo 
"Se ha redimensionado correctamente";
            echo 
"<br> Esto es el nombre de original $nombre_comple";
            echo 
"<br> Esto es el nombre de original $copia";
            
    
$consulta=mysql_query("INSERT INTO imagenes (id,nombre,miniatura,id_logueado,fecha) VALUES ('null','$nombre_comple','$mini_comple','$id_usuario','".$fecha."')"$conexion)or
  die(
"Problemas en el select:".mysql_error());
         
    } else {
        echo 
"La imagen debe tener un ancho mayor que 120";
    }
}
$resultados=mysql_query("select * from imagenes where id_logueado='$id_usuario'",$conexion) or
  die(
"Problemas en el select:".mysql_error());?><div id="galeria">
  <?php
  
function mandar_datos()
  {
      
alert('holaa');
  }
while(
$res=mysql_fetch_assoc($resultados))
{
    
?> <A href="<?php echo $res['nombre'];?>" title=""><img src="<?php echo $res['miniatura'];?>"><A>
     <?php
     
}
?></div>
<?php }echo "$obejeto"?><a href="datos_necesi.php">esto es prueba</a>
No me entra en uno lo pongo en el siguiente el lightbox.js
  #19 (permalink)  
Antiguo 27/12/2011, 14:39
 
Fecha de Ingreso: noviembre-2011
Mensajes: 516
Antigüedad: 12 años, 5 meses
Puntos: 10
Respuesta: codigo pho en javascript

lightbox.js parte 1
Código PHP:
/**
 * jQuery lightBox plugin
 * This jQuery plugin was inspired and based on Lightbox 2 by Lokesh Dhakar (http://www.huddletogether.com/projects/lightbox2/)
 * and adapted to me for use like a plugin from jQuery.
 * @name jquery-lightbox-0.5.js
 * @author Leandro Vieira Pinho - http://leandrovieira.com
 * @version 0.5
 * @date April 11, 2008
 * @category jQuery plugin
 * @copyright (c) 2008 Leandro Vieira Pinho (leandrovieira.com)
 * @license CCAttribution-ShareAlike 2.5 Brazil - http://creativecommons.org/licenses/by-sa/2.5/br/deed.en_US
 * @example Visit http://leandrovieira.com/projects/jquery/lightbox/ for more informations about this jQuery plugin
 */

// Offering a Custom Alias suport - More info: http://docs.jquery.com/Plugins/Authoring#Custom_Alias
(function($) {
    
/**
     * $ is an alias to jQuery object
     *
     */
    
$.fn.lightBox = function(settings) {
        
// Settings to configure the jQuery lightBox plugin how you like
        
settings jQuery.extend({
            
// Configuration related to overlay
            
overlayBgColor:         '#2E9AFE',        // (string) Background color to overlay; inform a hexadecimal value like: #RRGGBB. Where RR, GG, and BB are the hexadecimal values for the red, green, and blue values of the color.
            
overlayOpacity:            0.2,        // (integer) Opacity value to overlay; inform: 0.X. Where X are number from 0 to 9
            // Configuration related to navigation
            
fixedNavigation:        false,        // (boolean) Boolean that informs if the navigation (next and prev button) will be fixed or not in the interface.
            // Configuration related to images
            
imageLoading:            'images/lightbox-ico-loading.gif',        // (string) Path and the name of the loading icon
            
imageBtnPrev:            'images/lightbox-btn-prev.gif',            // (string) Path and the name of the prev button image
            
imageBtnNext:            'images/lightbox-btn-next.gif',            // (string) Path and the name of the next button image
            
imageBtnClose:            'images/lightbox-btn-close.gif',        // (string) Path and the name of the close btn
            
imageBlank:                'images/lightbox-blank.gif',            // (string) Path and the name of a blank image (one pixel)
            // Configuration related to container image box
            
containerBorderSize:    10,            // (integer) If you adjust the padding in the CSS for the container, #lightbox-container-image-box, you will need to update this value
            
containerResizeSpeed:    400,        // (integer) Specify the resize duration of container image. These number are miliseconds. 400 is default.
            // Configuration related to texts in caption. For example: Image 2 of 8. You can alter either "Image" and "of" texts.
            
txtImage:                'Imagen',    // (string) Specify text "Image"
            
txtOf:                    'de',        // (string) Specify text "of"
            // Configuration related to keyboard navigation
            
keyToClose:                'c',        // (string) (c = close) Letter to close the jQuery lightBox interface. Beyond this letter, the letter X and the SCAPE key is used to.
            
keyToPrev:                'p',        // (string) (p = previous) Letter to show the previous image
            
keyToNext:                'n',        // (string) (n = next) Letter to show the next image.
            // Don´t alter these variables in any way
            
imageArray:                [],
            
activeImage:            0
        
},settings);
        
// Caching the jQuery object with all elements matched
        
var jQueryMatchedObj this// This, in this context, refer to jQuery object
        /**
         * Initializing the plugin calling the start function
         *
         * @return boolean false
         */
function _initialize() {
            
_start(this,jQueryMatchedObj); // This, in this context, refer to object (link) which the user have clicked
            
return false// Avoid the browser following the link
        
}
        
/**
         * Start the jQuery lightBox plugin
         *
         * @param object objClicked The object (link) whick the user have clicked
         * @param object jQueryMatchedObj The jQuery object with all elements matched
         */
        
function _start(objClicked,jQueryMatchedObj) {
            
// Hime some elements to avoid conflict with overlay in IE. These elements appear above the overlay.
            
$('embed, object, select').css({ 'visibility' 'hidden' });
            
// Call the function to create the markup structure; style some elements; assign events in some elements.
            
_set_interface();
            
// Unset total images in imageArray
            
settings.imageArray.length 0;
            
// Unset image active information
            
settings.activeImage 0;
            
// We have an image set? Or just an image? Let´s see it.
            
if ( jQueryMatchedObj.length == ) {
                
settings.imageArray.push(new Array(objClicked.getAttribute('href'),objClicked.getAttribute('title')));
            } else {
                
// Add an Array (as many as we have), with href and title atributes, inside the Array that storage the images references        
                
for ( var 0jQueryMatchedObj.lengthi++ ) {
                    
settings.imageArray.push(new Array(jQueryMatchedObj[i].getAttribute('href'),jQueryMatchedObj[i].getAttribute('title')));
                }
            }
            while ( 
settings.imageArray[settings.activeImage][0] != objClicked.getAttribute('href') ) {
                
settings.activeImage++;
            }
            
// Call the function that prepares image exibition
            
_set_image_to_view();
        }
        
/**
         * Create the jQuery lightBox plugin interface
         *
         * The HTML markup will be like that:
            <div id="jquery-overlay"></div>
            <div id="jquery-lightbox">
                <div id="lightbox-container-image-box">
                    <div id="lightbox-container-image">
                        <img src="../fotos/XX.jpg" id="lightbox-image">
                        <div id="lightbox-nav">
                            <a href="#" id="lightbox-nav-btnPrev"></a>
                            <a href="#" id="lightbox-nav-btnNext"></a>
                        </div>
                        <div id="lightbox-loading">
                            <a href="#" id="lightbox-loading-link">
                                <img src="../images/lightbox-ico-loading.gif">
                            </a>
                        </div>
                    </div>
                </div>
                <div id="lightbox-container-image-data-box">
                    <div id="lightbox-container-image-data">
                        <div id="lightbox-image-details">
                            <span id="lightbox-image-details-caption"></span>
                            <span id="lightbox-image-details-currentNumber"></span>
                        </div>
                        <div id="lightbox-secNav">
                            <a href="#" id="lightbox-secNav-btnClose">
                                <img src="../images/lightbox-btn-close.gif">
                            </a>
                        </div>
                    </div>
                </div>
            </div>
         *
         */
        
function _set_interface() {
            
// Apply the HTML markup into body tag
            
$('body').append('<div id="jquery-overlay"></div><div id="jquery-lightbox"><div id="lightbox-container-image-box"><div id="lightbox-container-image"><img id="lightbox-image"><div style="" id="lightbox-nav"><a href="#" id="lightbox-nav-btnPrev"></a><a href="#" id="lightbox-nav-btnNext"></a></div><div id="lightbox-loading"><a href="#" id="lightbox-loading-link"><img src="' settings.imageLoading '"></a></div></div></div><div id="lightbox-container-image-data-box"><div id="lightbox-container-image-data"><div id="lightbox-image-details"><span id="lightbox-image-details-caption"></span><span id="lightbox-image-details-currentNumber"></span></div><div id="lightbox-secNav"><a href="#" id="lightbox-secNav-btnClose"><img src="' settings.imageBtnClose '"></a></div></div></div><div class="comentarios"><textarea name="nombre"></textarea></div></div>');    
            
// Get page sizes
            
var arrPageSizes ___getPageSize();
            
// Style overlay and show it
            
$('#jquery-overlay').css({
                
backgroundColor:    settings.overlayBgColor,
                
opacity:            settings.overlayOpacity,
                
width:                arrPageSizes[0],
                
height:                arrPageSizes[1]
            }).
fadeIn();
            
// Get page scroll
            
var arrPageScroll ___getPageScroll();
            
// Calculate top and left offset for the jquery-lightbox div object and show it
            
$('#jquery-lightbox').css({
                
top:    arrPageScroll[1] + (arrPageSizes[3] / 10),
                
left:    arrPageScroll[0]
            }).
show();
            
// Assigning click events in elements to close overlay
            
            // Assign the _finish function to lightbox-loading-link and lightbox-secNav-btnClose objects
            
$('#lightbox-loading-link,#lightbox-secNav-btnClose').click(function() {
                
_finish();
                return 
false;
            });
            
// If window was resized, calculate the new overlay dimensions
            
$(window).resize(function() {
                
// Get page sizes
                
var arrPageSizes ___getPageSize();
                
// Style overlay and show it
                
$('#jquery-overlay').css({
                    
width:        arrPageSizes[0],
                    
height:        arrPageSizes[1]
                });
                
// Get page scroll
                
var arrPageScroll ___getPageScroll();
                
// Calculate top and left offset for the jquery-lightbox div object and show it
                
$('#jquery-lightbox').css({
                    
top:    arrPageScroll[1] + (arrPageSizes[3] / 10),
                    
left:    arrPageScroll[0]
                });
            });
        }
        
/**
         * Prepares image exibition; doing a image´s preloader to calculate it´s size
         *
         */
        
function _set_image_to_view() { // show the loading
            // Show the loading
            
$('#lightbox-loading').show();
            if ( 
settings.fixedNavigation ) {
                $(
'#lightbox-image,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber').hide();
            } else {
                
// Hide some elements
                
$('#lightbox-image,#lightbox-nav,#lightbox-nav-btnPrev,#lightbox-nav-btnNext,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber').hide();
            }
            
// Image preload process
            
var objImagePreloader = new Image();
            
objImagePreloader.onload = function() {
                $(
'#lightbox-image').attr('src',settings.imageArray[settings.activeImage][0]);
                
// Perfomance an effect in the image container resizing it
                
_resize_container_image_box(objImagePreloader.width,objImagePreloader.height);
                
//    clear onLoad, IE behaves irratically with animated gifs otherwise
                
objImagePreloader.onload=function(){};
            };
            
objImagePreloader.src settings.imageArray[settings.activeImage][0];
        };
        
/**
         * Perfomance an effect in the image container resizing it
         *
         * @param integer intImageWidth The image´s width that will be showed
         * @param integer intImageHeight The image´s height that will be showed
         */ 
  #20 (permalink)  
Antiguo 27/12/2011, 14:41
 
Fecha de Ingreso: noviembre-2011
Mensajes: 516
Antigüedad: 12 años, 5 meses
Puntos: 10
Respuesta: codigo pho en javascript

parte 2
Código PHP:
function _resize_container_image_box(intImageWidth,intImageHeight) {
            
// Get current width and height
            
var intCurrentWidth = $('#lightbox-container-image-box').width();
            var 
intCurrentHeight = $('#lightbox-container-image-box').height();
            
// Get the width and height of the selected image plus the padding
            
var intWidth = (intImageWidth + (settings.containerBorderSize 2)); // Plus the image´s width and the left and right padding value
            
var intHeight = (intImageHeight + (settings.containerBorderSize 2)); // Plus the image´s height and the left and right padding value
            // Diferences
            
var intDiffW intCurrentWidth intWidth;
            var 
intDiffH intCurrentHeight intHeight;
            
// Perfomance the effect
            
$('#lightbox-container-image-box').animate({ widthintWidthheightintHeight },settings.containerResizeSpeed,function() { _show_image(); });
            if ( ( 
intDiffW == ) && ( intDiffH == ) ) {
                if ( $.
browser.msie ) {
                    
___pause(250);
                } else {
                    
___pause(100);    
                }
            } 
            $(
'#lightbox-container-image-data-box').css({ widthintImageWidth });
            $(
'#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({ heightintImageHeight + (settings.containerBorderSize 2) });
        };
        
/**
         * Show the prepared image
         *
         */
        
function _show_image() {
            $(
'#lightbox-loading').hide();
            $(
'#lightbox-image').fadeIn(function() {
                
_show_image_data();
                
_set_navigation();
            });
            
_preload_neighbor_images();
        };
        
/**
         * Show the image information
         *
         */
        
function _show_image_data() {
            $(
'#lightbox-container-image-data-box').slideDown('fast');
            $(
'#lightbox-image-details-caption').hide();
            if ( 
settings.imageArray[settings.activeImage][1] ) {
                $(
'#lightbox-image-details-caption').html(settings.imageArray[settings.activeImage][1]).show();
            }
            
// If we have a image set, display 'Image X of X'
            
if ( settings.imageArray.length ) {
                $(
'#lightbox-image-details-currentNumber').html(settings.txtImage ' ' + ( settings.activeImage ) + ' ' settings.txtOf ' ' settings.imageArray.length).show();
            }        
        }
        
/**
         * Display the button navigations
         *
         */
        
function _set_navigation() {
            $(
'#lightbox-nav').show();

            
// Instead to define this configuration in CSS file, we define here. And it´s need to IE. Just.
            
$('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({ 'background' 'transparent url(' settings.imageBlank ') no-repeat' });
            
            
// Show the prev button, if not the first image in set
            
if ( settings.activeImage != ) {
                if ( 
settings.fixedNavigation ) {
                    $(
'#lightbox-nav-btnPrev').css({ 'background' 'url(' settings.imageBtnPrev ') left 15% no-repeat' })
                        .
unbind()
                        .
bind('click',function() {
                            
settings.activeImage settings.activeImage 1;
                            
_set_image_to_view();
                            return 
false;
                        });
                } else {
                    
// Show the images button for Next buttons
                    
$('#lightbox-nav-btnPrev').unbind().hover(function() {
                        $(
this).css({ 'background' 'url(' settings.imageBtnPrev ') left 15% no-repeat' });
                    },function() {
                        $(
this).css({ 'background' 'transparent url(' settings.imageBlank ') no-repeat' });
                    }).
show().bind('click',function() {
                        
settings.activeImage settings.activeImage 1;
                        
_set_image_to_view();
                        return 
false;
                    });
                }
            }
            
            
// Show the next button, if not the last image in set
            
if ( settings.activeImage != ( settings.imageArray.length -) ) {
                if ( 
settings.fixedNavigation ) {
                    $(
'#lightbox-nav-btnNext').css({ 'background' 'url(' settings.imageBtnNext ') right 15% no-repeat' })
                        .
unbind()
                        .
bind('click',function() {
                            
settings.activeImage settings.activeImage 1;
                            
_set_image_to_view();
                            return 
false;
                        });
                } else {
                    
// Show the images button for Next buttons
                    
$('#lightbox-nav-btnNext').unbind().hover(function() {
                        $(
this).css({ 'background' 'url(' settings.imageBtnNext ') right 15% no-repeat' });
                    },function() {
                        $(
this).css({ 'background' 'transparent url(' settings.imageBlank ') no-repeat' });
                    }).
show().bind('click',function() {
                        
settings.activeImage settings.activeImage 1;
                        
_set_image_to_view();
                        return 
false;
                    });
                }
            }
            
// Enable keyboard navigation
            
_enable_keyboard_navigation();
        }
        
/**
         * Enable a support to keyboard navigation
         *
         */
        
function _enable_keyboard_navigation() {
            $(
document).keydown(function(objEvent) {
                
_keyboard_action(objEvent);
            });
        }
        
/**
         * Disable the support to keyboard navigation
         *
         */
        
function _disable_keyboard_navigation() {
            $(
document).unbind();
        }
        
/**
         * Perform the keyboard actions
         *
         */
        
function _keyboard_action(objEvent) {
            
// To ie
            
if ( objEvent == null ) {
                
keycode event.keyCode;
                
escapeKey 27;
            
// To Mozilla
            
} else {
                
keycode objEvent.keyCode;
                
escapeKey objEvent.DOM_VK_ESCAPE;
            }
            
// Get the key in lower case form
            
key String.fromCharCode(keycode).toLowerCase();
            
// Verify the keys to close the ligthBox
            
if ( ( key == settings.keyToClose ) || ( key == 'x' ) || ( keycode == escapeKey ) ) {
                
_finish();
            }
            
// Verify the key to show the previous image
            
if ( ( key == settings.keyToPrev ) || ( keycode == 37 ) ) {
                
// If we´re not showing the first image, call the previous
                
if ( settings.activeImage != ) {
                    
settings.activeImage settings.activeImage 1;
                    
_set_image_to_view();
                    
_disable_keyboard_navigation();
                }
            }
            
// Verify the key to show the next image
            
if ( ( key == settings.keyToNext ) || ( keycode == 39 ) ) {
                
// If we´re not showing the last image, call the next
                
if ( settings.activeImage != ( settings.imageArray.length ) ) {
                    
settings.activeImage settings.activeImage 1;
                    
_set_image_to_view();
                    
_disable_keyboard_navigation();
                }
            }
        }
        
/**
         * Preload prev and next images being showed
         *
         */
        
function _preload_neighbor_images() {
            if ( (
settings.imageArray.length -1) > settings.activeImage ) {
                
objNext = new Image();
                
objNext.src settings.imageArray[settings.activeImage 1][0];
            }
            if ( 
settings.activeImage ) {
                
objPrev = new Image();
                
objPrev.src settings.imageArray[settings.activeImage -1][0];
            }
        }
        
/**
         * Remove jQuery lightBox plugin HTML markup
         *
         */
        
function _finish() {
            $(
'#jquery-lightbox').remove();
            $(
'#jquery-overlay').fadeOut(function() { $('#jquery-overlay').remove(); });
            
// Show some elements to avoid conflict with overlay in IE. These elements appear above the overlay.
            
$('embed, object, select').css({ 'visibility' 'visible' });
        }
        
/**
         / THIRD FUNCTION
         * getPageSize() by quirksmode.com
         *
         * @return Array Return an array with page width, height and window width, height
         */
        
function ___getPageSize() {
            var 
xScrollyScroll;
            if (
window.innerHeight && window.scrollMaxY) {    
                
xScroll window.innerWidth window.scrollMaxX;
                
yScroll window.innerHeight window.scrollMaxY;
            } else if (
document.body.scrollHeight document.body.offsetHeight){ // all but Explorer Mac
                
xScroll document.body.scrollWidth;
                
yScroll document.body.scrollHeight;
            } else { 
// Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
                
xScroll document.body.offsetWidth;
                
yScroll document.body.offsetHeight;
            }
            var 
windowWidthwindowHeight;
            if (
self.innerHeight) {    // all except Explorer
                
if(document.documentElement.clientWidth){
                    
windowWidth document.documentElement.clientWidth
                } else {
                    
windowWidth self.innerWidth;
                }
                
windowHeight self.innerHeight;
            } else if (
document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
                
windowWidth document.documentElement.clientWidth;
                
windowHeight document.documentElement.clientHeight;
            } else if (
document.body) { // other Explorers
                
windowWidth document.body.clientWidth;
                
windowHeight document.body.clientHeight;
            }    
            
// for small pages with total height less then height of the viewport
            
if(yScroll windowHeight){
                
pageHeight windowHeight;
            } else { 
                
pageHeight yScroll;
            }
            
// for small pages with total width less then width of the viewport
            
if(xScroll windowWidth){    
                
pageWidth xScroll;        
            } else {
                
pageWidth windowWidth;
            }
            
arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
            return 
arrayPageSize;
        };
        
/**
         / THIRD FUNCTION
         * getPageScroll() by quirksmode.com
         *
         * @return Array Return an array with x,y page scroll values.
         */
        
function ___getPageScroll() {
            var 
xScrollyScroll;
            if (
self.pageYOffset) {
                
yScroll self.pageYOffset;
                
xScroll self.pageXOffset;
            } else if (
document.documentElement && document.documentElement.scrollTop) {     // Explorer 6 Strict
                
yScroll document.documentElement.scrollTop;
                
xScroll document.documentElement.scrollLeft;
            } else if (
document.body) {// all other Explorers
                
yScroll document.body.scrollTop;
                
xScroll document.body.scrollLeft;    
            }
            
arrayPageScroll = new Array(xScroll,yScroll);
            return 
arrayPageScroll;
        };
         
/**
          * Stop the code execution from a escified time in milisecond
          *
          */
         
function ___pause(ms) {
            var 
date = new Date(); 
            
curDate null;
            do { var 
curDate = new Date(); }
            while ( 
curDate date ms);
         };
        
// Return the jQuery object for chaining. The unbind method is used to avoid click conflict when the plugin is called more than once
        
return this.unbind('click').click(_initialize);
    };
    var 
objeto="hola";
})(
jQuery); // Call and execute the function immediately passing the jQuery object 
  #21 (permalink)  
Antiguo 28/12/2011, 15:59
 
Fecha de Ingreso: noviembre-2011
Mensajes: 516
Antigüedad: 12 años, 5 meses
Puntos: 10
Respuesta: codigo pho en javascript

Cita:
Iniciado por dggluz Ver Mensaje
No conozco Lightbox (sí Fancybox), así que mucho no te puedo orientar. Pero es probable que tu solución no sea trivial. Muestra tu código, porque sino se me va a hacer muy difícil ayudarte. ¡Suerte!
con fancybox tambien me vale la ayuda ya es que nose como hacerlo quiero ponerle comentarios debajo de la foto con un campo de texto para que los usuarios comenten. gracias.

Etiquetas: js, pho, php
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 12:03.