Pregunta

Con jQuery, cambio el src de una imagen al hacer clic

$("#thumb li img").click(function() {
var newlinkimage = $(this).attr("src");

newlinkimage = newlinkimage.substring(14,17);

    $("#avant img").attr("src", 'retouche-hr' + newlinkimage + '-a.jpg');
    $("#apres img").attr("src", 'retouche-hr' +newlinkimage + '-b.jpg');

El problema es que el NUEVO ancho de imagen es diferente al anterior. ¿CÓMO obtengo el ancho NATIVO de la nueva imagen (como la pequeña flecha que aparece en Dreamweaver?

¿Fue útil?

Solución

Esta es la forma simple de javascript para hacerlo. Debería ser fácil integrar esto en su código.

var newimage = new Image();
newimage.src = 'retouche-hr' + newlinkimage + '-a.jpg'; // path to image
var width = newimage.width;
var height = newimage.height;

Otros consejos

¿La imagen anterior tenía un ancho y una altura establecidos? Si usa $ (imagen) .width (" ") debería restablecer el ancho a lo que era antes de aplicarle cualquier cambio de ancho (de manera similar para la altura). Sin embargo, no creo que esto funcione para las imágenes que tenían su ancho establecido a través de CSS o la propiedad. Después de restablecer el ancho anterior, puede usar .outerWidth () para obtener el ancho de la imagen.

Desea obtener el ancho real de la imagen antes de cambiarla, luego configure la nueva imagen en ese ancho. puedes hacer esto con $ (img) .load:

var pic_real_width;
var pic_real_height;

$(img).load(function() {
    // need to remove these in of case img-element has set width and height
    $(this).removeAttr("width")
           .removeAttr("height");

    pic_real_width = this.width;
    pic_real_height = this.height;
});

$("#thumb li img").click(function() {
var newlinkimage = $(this).attr("src");

newlinkimage = newlinkimage.substring(14,17);

        $("#avant img").attr("src", 'retouche-hr' + newlinkimage + '-a.jpg').width(pic_real_width);
        $("#apres img").attr("src", 'retouche-hr' +newlinkimage + '-b.jpg').width(pic_real_width);

este código siempre devuelve Cero '0'

    var newimage = new Image();
    newimage.src = 'retouche-hr' + newlinkimage.substring(14,17) + '-a.jpg'; 
    var width = newimage.naturalWidth;
    var height = newimage.naturalHeight;
    alert (width);

¿POR QUÉ ???

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top