javascript - how to copy div content to another pa

2019-02-11 06:51发布

问题:

I would like to make an automatic copy of a div content from page 1 an paste it in a div on page 2 ? What's the best, easiest way to achieve this ?

回答1:

For javascript only and with HTML5 support,

Page 1:

var pageContent = document.getElementById("myDiv1").innerHTML; 
sessionStorage.setItem("page1content", pageContent);

Page 2:

document.getElementById("myDiv2").innerHTML=sessionStorage.getItem("page1content");


回答2:

Depending on your requirements, you could save the value of the div in the LocalStorage when they clip to copy, and then read it from LocalStorage when they click paste. That is the easiest.

Unfortunately, if you want to actually put something on their system's clipboard, you will need to use Flash.



回答3:

I think the easiest way to do this is using an Iframe. YOu just view the contents of page1 and display it at page2.

A quick example:

<iframe name="inlineframe" src="pag1.html" frameborder="0" scrolling="auto" width="500" height="500" marginwidth="5" marginheight="5" ></iframe>

This is one 'simple' solution. But ofcourse there are other methods. This solution is easy because you don't need jquery.



回答4:

This is easier done with jQuery but you can get the html of a div using innerHTML as such:

var div1 = document.getElementById('div1'),
div1html = div1.innerHTML;

Copying it to a div on a different page however would require some work..

I know this doesn't answer your question entirely, I'm just giving you some insight as to how to get the html of an element. Copying it, using JS, could go something like this:

var div2 = document.getElementById('div2')
div2.appendChild(div1.cloneNode(true));