网页重置并停止应用CSS

时间:2014-12-10 06:38:12

标签: javascript html css

我正在为课堂制作一个网页,其中包含使用JavaScript构建自己的故事。开始时,用户输入他们的姓名并选择他们的性别(点击代表性别的图像),然后我使用removeChild使性别图像消失,并以不包括标题的新页面开始故事。但是一旦用户选择了性别,我应用的CSS似乎被网页忽略 - 黑色背景变为白色,文本居中被忽略。为什么会这样,我怎样才能通过网页保持CSS一致,同时仍然按照我的意愿去做?

HTML:

var name = prompt("Welcome! To begin, please tell me your name:");
    var gender = 0;
    var maleImage = 0;
    var femaleImage = 0;
    var genderPrompt = 0;

    document.writeln("<h2>Hello " + name + "! Welcome to Design Your Own Story! " + 
                     "In this game, you pick how the story goes!</h2><h2 id='genderPrompt'>Let's begin. Click which gender you are.</h2>");

    document.writeln("<img id='maleImage' src='maleImage.jpg' alt='Male Image' onclick='genderChoice(1)' />");
    document.writeln("<img id='femaleImage' src='femaleImage.jpg' alt='Female Image' onclick='genderChoice(2)' />");

    function genderChoice(genderImage) {
        if (genderImage === 1) {
            gender = "male";
        } else {
            gender = "female";
        }
        setTimeout(genderReset,250);

    }

    function genderReset() {
        if (gender === "female") {  
            maleImage = document.getElementById("maleImage");
            maleImage.parentNode.removeChild(maleImage);
        }
        if (gender === "male") {
            femaleImage = document.getElementById("femaleImage");
            femaleImage.parentNode.removeChild(femaleImage);
        }
        genderPrompt = document.getElementById("genderPrompt");
        genderPrompt.parentNode.removeChild(genderPrompt);

        document.writeln("<h1 class='title'>Design Your Own Story</h1>");
        document.writeln("<h2>Ok, " + name + ", so you're " + gender + "! Let's start our journey...</h2>");
        setTimeout(leavesHome,1500);
    }

CSS:

* {
    background-color:black;
    color:white;
    text-align:center;
}

img {
    width:30%;
}

2 个答案:

答案 0 :(得分:0)

javascript无法识别genderCoice功能。您可能正在关闭中运行代码。

尝试将其分配给一个对象(我以document为例,虽然这不一定是最佳做法):

document.genderChoice = function(genderImage) {
    if (genderImage === 1) {
        gender = "male";
    } else {
        gender = "female";
    }
    setTimeout(genderReset,250);

}

请参阅this工作。 (小提琴本身坏了,可能是因为writeln,无法进一步编辑)

答案 1 :(得分:0)

我认为问题在于您在文档加载完成后尝试使用document.writeln。一旦文档关闭,您应该只对打开的文档使用document.writeln document.writeln将导致内容被删除。这就是擦除你的样式表。

要在加载页面后修改页面,您应该执行以下操作:

var div = document.createElement('div');
div.innerHTML = "<span>Some new text here</span>";

或者在索引页面中预先创建元素,然后使用它们来设置innerHtml:

<body>
   <div id="section"></div>
</body>

然后在你的代码中:

var section = document.getElementById("section");
section.innerHTML = "<span>Some new text goes here</span>";