简体   繁体   中英

Clone image inside a div

In the code I am writing I am attempting to clone a picture from inside a list and insert it inside a div. The image is also draggable to the div.

For reference this is how I have my image in my HTML code

  <img id="drag1" src="https://pixabay.com/get/19b738fe047c3bf9d39b/1440605897/smiley-163510_1280.jpg?direct" draggable="true" ondragstart="drag(event)" width=200px length=200px>

Here is part of my test.js code:

$("#buttona").click(function () {

  $('#drag1').clone().insertAfter("#maindiv");

});

I have two issues.

  1. How to I get it to copy inside my div. I only am aware of .insertAfter or .insertBefore

  2. Currently I can get it to insert the clone image after the div I want but the cloned image is behind another image. How can I get it to show up in front. I tried changing the z-index of the 2 images but it didnt change anything for the clone image, it was still behind the other image.

The commenter is correct, use .appendTo() instead of .insertAfter() . For an image to respect z-index , it must be either relatively or absolutely positioned, so in your CSS:

<some-image-selector-rule> {
   position: absolute; --or--
   position: relative;
}

You're question is two fold. The first being how to insert the image. For this jQuery has several helpful methods including .append() , .html() , .appendTo , etc. For a full list of jQuery DOM manipulation functions see this list .

On to your questions. A simple solution would be to use:

$("#buttona").click(function () {
    $('#drag1')
        .clone()
        .attr('id', 'drag2')   // <-- Note this line
        .appendTo("#maindiv");
});

Note the added .attr('id', 'drag2') . It is invalid to have two elements within the DOM with the same ID. Once you clone the element, you'll need to change the ID.

As for your second question, z-index only applies to elements that contain a position attribute. See this MDN article for reference. To get this image to show above the other, you'll need to modify your CSS:

#drag2 {
    position: relative;
    z-index: 1;
}

or inline the CSS as part of your previous operation:

$("#buttona").click(function () {
    $('#drag1')
        .clone()
        .attr('id', 'drag2')
        .css({ 'position': 'relative', 'z-index': 1 })
        .appendTo("#maindiv");
});

You're z-index problem may be solved for you however, by placing the image in the correct location (ie inside the <div> instead of after it). Try that fix first to see if the z-index is really needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM