clone/copy DOM element function not working proper

2019-09-14 22:23发布

问题:

My question is different than this because that code is not working on clicking the clone button, i have explained how that code is working with the help of an video. I am not getting any response on that thread so after waiting for 3 days, i am posting this question for further help.

I have a very basic requirement. When i right click on a element it shows a context menu, this menu has a clone button. What i want is when this button is clicked it should clone or copy the same element next to this selected element.

Problem i am facing, when i right click > i get the menu > when i click on clone my function will not return value, it will return value if i again right click, secondly i am unable to append it below selected text, below is my code:

My editpage.ts code, function used is clone()

//for clone
  clone(){
    console.log("clone function here");
  document.addEventListener("contextmenu", (e) => {
  e.preventDefault();
  console.log(e, e.srcElement.outerHTML);
  this.htmlstring = e.srcElement.outerHTML;
});
  }

  // code for right click context menu
  rightPanelStyle: Object = {};

  detectRightMouseClick($event) {
    // disabling the default browser window which comes on right click
    document.addEventListener('contextmenu', event => event.preventDefault());

       if($event.which === 3) {
           this.rightPanelStyle = {'display':'block','left':$event.clientX + 'px','top':$event.clientY + 'px'};
            return false;
       }
  }

Below showing a small 20 second video of what exactly is happening - http://youtu.be/I4nAb77lk_Q?hd=1

Please please help

回答1:

You can use "cloneNode(true)" function to clone elements. parameter passing to the function says clone elements with its child nodes.

document.addEventListener('contextmenu', function(e) {
  var targetElement = e.target;
  clone = targetElement.cloneNode(true);
  targetElement.appendChild(clone);
})

In your code, attaching "contextmenu" event inside the clone() function. If you invoke that when initiating your code, it would be good. If not I recommend to do it when initiating your code. Otherwise contextmenu event will be attaching after you call clone function.

Hope this help.