提问者:小点点

单击按钮/表单提交后,CSS样式表不会出现


单击use按钮后,当我检查页面时,源显示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;
    })
}

任何帮助都是如此感激!


共2个答案

匿名用户

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

摘自https://developer.mozilla.org/en-us/docs/web/api/document/write:

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

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

匿名用户

与其使用覆盖html的Document.write,您可以尝试以下方法:

    <input type="submit" value="Use" class="submit">

    <!-- add new div to show the result -->
    <div id="result"></div>

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

在click事件中:

useBtn.addEventListener('click', function(){
    let person = document.querySelector('.fname').value;
    let res = document.getElementById('result');

    res.innerHTML = "<h2>It's "+person+"'s turn!</h2>";
    // add further information to innerHTML here
    // hide input fname and submit button

    redoBtn();

})