这段代码结果为何颜色css没有被执行?

<script>
    function amo()
    {
        document.write("<div class='x'>eee</div>")

        document.write("<div class='x'>eee</div>")

        document.write("<div class='x'>eee</div>")
    }

</script>
<style>
    .x{width:50px;height:50px;background-color:red;}
</style>

<input type=button onclick='amo()' value='fff'>
阅读 2.9k
5 个回答

因为document.write会重写整个html的内容
原先是这样的
图片描述
而你点击之后,页面源码变成了这样
图片描述

也就是只有amo里面的内容了
你的style样式都被覆盖替换掉了

document.write();head里的style都写掉了。。

因为用了,document.writedocument.write会清除掉所有的doucment的内容,因此你写的style也会被清除掉,你用“审元素”看一下,会发现dom里只有你write的元素了。

document.write 把原来的网页覆盖了 所以你写的style也就不存在了

你直接用 document.write 把原文档都覆盖 了,你打开你的页面看看,

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题