首页 > 解决方案 > 单击按钮/表单提交后,CSS样式表不出现

问题描述

单击使用按钮后,我检查页面时的来源显示 style.css 页面消失了,并且没有应用任何样式。我无法弄清楚为什么会这样。

我的 index.html 页面如下所示:

<!DOCTYPE html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title></title>
        <meta name="description" content="">
        <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500&family=Roboto:wght@100;300;400;700&display=swap" rel="stylesheet">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="style.css">
    </head>
    <body>

        <input type="text" placeholder="First name" class="fname">
        <input type="submit" value="Use" class="submit">


        <script src="app.js"></script>
    </body>
</html>

我的 app.js 是这样的:


const useBtn = document.querySelector('.submit');
const reloadBtn = document.querySelector('.btn__reload')

document.body.style.fontFamily = "Roboto;"

useBtn.addEventListener('click', function(){
    let person = document.querySelector('.fname').value;
    document.write(`<h2>It's ${person}'s turn!</h2>`)
    document.write(`<h4>How long will they live?</h4>`)
    let oldAge = `<p>${Math.floor((Math.random() * 10)+ 30)}</p>`
    document.write(oldAge)
    document.write(`<h4>What will be their yearly salary?</h4>`)
    let salary = `<p>${Math.floor(Math.random() * 10000)}</p>`
    document.write(salary)
    document.write(`<h4>What will be their career</h4>`)
    const jobs = [ 'plumber', 'doctor', 'witch', 'president', 'trump supporter']
    let job =  Math.floor(Math.random() * jobs.length)
    document.write(jobs[job])
    redoBtn();

})

function redoBtn(){
    let tryAgain = document.createElement('button')
    document.body.appendChild(tryAgain)
    let buttonText = document.createTextNode('Try Again')
    tryAgain.appendChild(buttonText)
    tryAgain.addEventListener('click', function(){
        window.location.href = window.location.href;
    })
}

任何帮助都非常感谢!

标签: javascripthtmlcss

解决方案


document.write正在覆盖您的所有 html,包括您的链接样式表。

来自https://developer.mozilla.org/en-US/docs/Web/API/Document/write

注意:当 document.write 写入文档流时,在关闭(加载)的文档上调用 document.write 会自动调用 document.open,这将清除文档。

如果您真的想使用document.write,则需要将样式表链接重写到新文档中。但是最好只替换页面上某些容器元素的 html,例如body元素。


推荐阅读