简体   繁体   English

document.write中的元素对齐

[英]element alignment at document.write

i have the simple code below and when i run it the 我下面有简单的代码,当我运行它时

element is Aligned to the center but when i open it in a window and use document.write it goes without the defined style/alignment 元素与中心对齐,但是当我在窗口中打开并使用document.write时,它没有定义的样式/对齐方式

<!DOCTYPE html>
<html>
<body>



<p align="Center">This is a p element<br>

This is also a p element.<br>

This is also a p element - Click the button to open a doc.</p>

<button onclick="myFunction()">Try it</button>

<script>
    function myFunction() {
        win = window.open();
        win.document.open();
        var x = document.getElementsByTagName("p");
        for (var i = 0; i < x.length; i++) {
            win.document.write(x[i].innerHTML);
        }
    }
</script>

</body>
</html>

在此处输入图片说明


在此处输入图片说明


any idea how to keep the original format of the HTML while writing into another document ? 任何想法如何在写入另一个文档时保持HTML的原始格式?

thank you 谢谢

any idea how to keep the original format of the HTML while writing into another document ? 任何想法如何在写入另一个文档时保持HTML的原始格式?

You need to write outerHTML instead of innerHTML since align=center is the attribute of p which forms the outer part of the mark-up ( innerHTML won't have it) 您需要编写outerHTML而不是innerHTML因为align=centerp的属性,它构成了标记的外部部分( innerHTML没有它)

 win.document.write(x[i].outerHTML);

it is normal because innerHTML take the html inside the element but not the attributes of the element. 这是正常现象,因为innerHTML接受元素内部的html而不接受元素的属性。 So as "center" is an attribute it is not taken and so not centered. 因此,由于“中心”是一个属性,因此它不会被使用,因此不会居中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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