2011-11-09 14 views
7

Estoy tratando de subir algunas imágenes y mostrarlas dentro de un DIV vacío y después de subirlas si muevo el mouse sobre una imagen, debería obtener un ícono de eliminación para que los usuarios debería ser capaz de eliminarlo con una animación y mover la siguiente imagen a la posición de la imagen eliminada.Cómo adjuntar una imagen/icono de eliminación a la imagen dentro de div usando jquery

¿Cómo lo consigo?

Así es como yo estoy cargando y añadiendo a la div contenedor:

<script type="text/javascript"> 
$(function() { 
    document.getElementById('Nextbutton').style.visibility = "hidden"; // show 
    $("#uploader").plupload({ 
     // General settings 
     runtimes: 'gears,flash,silverlight,browserplus,html5', 
     url: 'Test.aspx', 
     max_file_size: '10mb', 
     max_file_count: 20, 
     chunk_size: '1mb', 
     unique_names: true, 

     filters: [ 
      { title: "Image files", extensions: "jpg,gif,png" }, 
      { title: "Zip files", extensions: "zip" } 
     ], 


     flash_swf_url: 'js/plupload.flash.swf', 


     silverlight_xap_url: 'js/plupload.silverlight.xap' 
    }); 



    $('form').submit(function (e) { 
     var uploader = $('#uploader').plupload('getUploader'); 

     if (uploader.files.length > 0) { 

      uploader.bind('StateChanged', function() { 
       if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) { 
        $('form')[0].submit(); 
       } 
      }); 

      uploader.start(); 

     } 
     else 
     //alert('You must at least upload one file.'); 

      return false; 
    }); 
    var uploader = $('#uploader').plupload('getUploader'); 

    uploader.bind('FilesAdded', function (up, files) { 
     //    jQuery('#container a').html(''); 
     $('#container > *').remove(); 
     var i = 0; 
     while (i++ < up.files.length) { 
      var ii = i; 
      while (ii < up.files.length) { 
       if (up.files[i - 1].name == up.files[ii].name) { 
        $.msgBox({ 
         title: "Ooops", 
         content: "There is already an image with the same filename and cannot be added.", 
         type: "error", 
         showButtons: true, 
         opacity: 0.9, 
         autoClose: false 
        }); 
        uploader.removeFile(up.files[ii]); 
       } else { 
        ii++; 
       } 
      } 
     } 
     if (i > 20) { 
      $.msgBox({ 
       title: "Info", 
       content: "Uuh! Please don't put me any more files.<br>Maximum Upload limit is only 20 Images.<br>Rest of the Images will be removed.", 
       type: "info", 
       showButtons: true, 
       opacity: 0.9, 
       autoClose: false 
      }); 
      $('#uploader_browse').hide(); 
     } 
    }); 
    uploader.bind('FilesRemoved', function (up, files) { 
     if (up.files.length < 20) { 
      $('#uploader_browse').fadeIn("slow"); 
     } 
    }); 


    uploader.bind('FileUploaded', function (up, file, res) { 
     $('#container').append("<div class='container a'><a href='uploads/" + document.getElementById("currentDirectory").value + "/" + file.name + "' rel='prettyPhoto' target='blank'><img src='uploads/" + document.getElementById("currentDirectory").value + "/" + file.name + "' width='64' height='64'/></a></div>"); 



     var $imageContainers = $('#container a'); 

     $imageContainers.each(function (index) { 
      $(this).delay(index * 50).fadeTo(400, 0.5); 
     }); 

     $imageContainers.mouseover(function() { 
      $(this).css('opacity', 1); 
      $(this).find('span.del').show(); 
     }); 
     $imageContainers.mouseout(function() { 
      $(this).css('opacity', 0.5); 
      $(this).find('span.del').hide(); 
     }); 



     if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) { 
      document.getElementById('Nextbutton').style.visibility = "visible"; // show 
      showStickySuccessToast(); 
     } 
     uploader.removeFile(file); 
    }); 

}); 


    function randomString(length) { 
     var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split(''); 

     if (!length) { 
      length = Math.floor(Math.random() * chars.length); 
     } 

     var str = ''; 
     for (var i = 0; i < length; i++) { 
      str += chars[Math.floor(Math.random() * chars.length)]; 
     } 
     return str; 
    } 

    </script> 

Aquí es mi div donde yo estoy mostrando las Imágenes:

<div id="container"> 
</div> 
+1

Este código tiene errores de sintaxis - necesita un soporte redondo de cierre para la llamada a ' .append' –

+0

Y también debería decirnos qué no funciona. – maxedison

+0

sí, simplemente no he colocado todo el código solo para saber dónde debo agregar la imagen – coder

Respuesta

11

Una demo está disponible en: http://jsfiddle.net/CWaHL/1/

HTML

<div id="container"> 
    <div class="image" id="image1" style="background-image:url(http://lorempixel.com/100/100/abstract);"> 
    <a href="#" class="delete">Delete</a> 
    </div> 
    <div class="image" id="image2" style="background-image:url(http://lorempixel.com/100/100/food);"> 
    <a href="#" class="delete">Delete</a> 
    </div> 
    <div class="image" id="image3" style="background-image:url(http://lorempixel.com/100/100/people);"> 
    <a href="#" class="delete">Delete</a> 
    </div> 
    <div class="image" id="image4" style="background-image:url(http://lorempixel.com/100/100/technics);"> 
    <a href="#" class="delete">Delete</a> 
    </div> 
</div> 

CSS

#container { overflow:auto; } 
.image { width:100px;height:100px;float:left;position:relative; } 
a.delete { display:none;position:absolute;top:0;right:0;width:30px;height:30px;text-indent:-999px;background:red; } 
.image:hover a.delete { display:block; } 

jQuery/Javascript

$(document).ready(function(){ 

    $('a.delete').on('click',function(e){ 
    e.preventDefault(); 
    imageID = $(this).closest('.image')[0].id; 
    alert('Now deleting "'+imageID+'"'); 
    $(this).closest('.image') 
     .fadeTo(300,0,function(){ 
     $(this) 
      .animate({width:0},200,function(){ 
      $(this) 
       .remove(); 
      }); 
     }); 
    }); 

}); 
+0

Gracias Lucanos esto es exactamente lo que necesito. – coder

+0

¡Esto es bueno! gracias – Roylee

+0

Exactamente lo que estaba buscando – Auspex

2

en este caso se puede establecer identificador como identificador, clase o nombre en la etiqueta img o cuando la etiqueta desea vincular evento ratón sobre. esta es la escritura que hace:

uploader.bind('FileUploaded', function (up, file, res) 
     { 
     $('#container').append("<div class='container a'> 
     <a href='uploads/" + document.getElementById("currentDirectory").value 
     + "/" + file.name + "' rel='prettyPhoto' target='blank'> 
     <img class="img-upload" src='uploads/" + document.getElementById("currentDirectory").value + "/" 
     + file.name + "' width='64' height='64'/> 
     </a> 
     </div>" 
} 
); 

estoy añadiendo class = "img-carga" en la etiqueta img, y será su uso en el próximo step.after esto se debe añadir detector de búsqueda de su elemento de clase. porque la imagen de su elemento no se genera cuando el navegador ejecuta javascript en la primera vez. ejemplo en document.ready. el elemento se generará después de subir la imagen, es decir, no puede hacer que el evento se active en el documento en document.ready porque el dom no está definido.

mi solución es: 1) hacer delegado de eventos o el ejemplo vivo: agrega este código en que la escritura

$(".container ").delegate(".img-upload", "mouseover", function() { 
    // show notification delete like icon 
}); 

o si eso no es un trabajo que puede probar este

$(".img-upload").live("mouseover", function(){ alert("get mouse over event"); }); 

y si desea utilizar el tiempo de espera para buscar el elemento en vivo o no, puede intentar esto debe agregar la identificación en su código de esta manera.

uploader.bind('FileUploaded', function (up, file, res) 
      { 
      $('#container').append("<div class='container a'> 
      <a href='uploads/" + document.getElementById("currentDirectory").value 
      + "/" + file.name + "' rel='prettyPhoto' target='blank'> 
      <img id="img-upload" src='uploads/" + document.getElementById("currentDirectory").value + "/" 
      + file.name + "' width='64' height='64'/> 
      </a> 
      </div>" 
    } 
    ); 


function waitForImg(){ 
var ele = document.getElementById(idImg); 
if(!ele){ 
    window.setTimeout(waitForImg, 100); 
} 
else{ 
    //you can show delete in here 
    $('#img-upload').mouseover(function() { 
    //show image delete 
    alert('show your icon delete'); 
}); 
} 
} 
waitForImg(); 
+0

Gracias por sus sugerencias Mohamad :) – coder

+0

de nada – viyancs

0

Puedo utilizar este código y funciona muy bien, después de esto usted tiene su foto en una entrada en su forma y hay que recibirlo y almacenarlo. Si tiene preguntas, hágamelo saber.

<div id="preview" class="thumbnail"> 
    <a href="#" id="file-select" class="btn btn-default">Select Photo</a> 
    <img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNzEiIGhlaWdodD0iMTgwIj48cmVjdCB3aWR0aD0iMTcxIiBoZWlnaHQ9IjE4MCIgZmlsbD0iI2VlZSI+PC9yZWN0Pjx0ZXh0IHRleHQtYW5jaG9yPSJtaWRkbGUiIHg9Ijg1LjUiIHk9IjkwIiBzdHlsZT0iZmlsbDojYWFhO2ZvbnQtd2VpZ2h0OmJvbGQ7Zm9udC1zaXplOjEycHg7Zm9udC1mYW1pbHk6QXJpYWwsSGVsdmV0aWNhLHNhbnMtc2VyaWY7ZG9taW5hbnQtYmFzZWxpbmU6Y2VudHJhbCI+MTcxeDE4MDwvdGV4dD48L3N2Zz4="/> 





    <input id="filename" name="filename" type="file" /> 

      </div> 


    <input type="submit" value="Upload Photo" id="file-save" class="btn btn-primary"/> 
    </div> 

este es el Javascript

<script> 
$('#preview').hover(
    function() { 
     $(this).find('a').fadeIn(); 
    }, function() { 
     $(this).find('a').fadeOut(); 
    } 
) 
$('#file-select').on('click', function(e) { 
    e.preventDefault(); 

    $('#filename').click(); 
}) 

$('input[type=file]').change(function() { 
    var file = (this.files[0].name).toString(); 
    var reader = new FileReader(); 

    $('#file-info').text(''); 
    $('#file-info').text(file); 

    reader.onload = function (e) { 
     $('#preview img').attr('src', e.target.result); 
    } 

    reader.readAsDataURL(this.files[0]); 
}); 
    </script> 

Este es el CSS:

body { 
    width: 300px; 
    margin: 10px auto; 
    text-align:center; 
} 
.thumbnail { 
    width: 120px; 
    margin: 0 auto; 
    margin-bottom: 10px; 
} 
.thumb { 
    width: 120px; 
    margin: 0; 
    margin-bottom: 10px; 


} 
#preview { 
    position: relative; 
} 
#preview a { 
    position: absolute; 
    bottom: 5px; 
    left: 5px; 
    right: 5px; 
    display: none; 
} 
#file-info { 
    text-align: center; 
    display: block; 
} 
input[type=file] { 
    position: absolute; 
    visibility: hidden; 
    width: 0; 
    z-index: -9999; 
} 
#file-save { 
    text-align:center; 
    width: 140px; 
} 
footer { 
    margin: 10px 0; 
} 
Cuestiones relacionadas