0

一般来说,我是 JavaScript 和网页设计的新手,我不明白为什么这不起作用。

有两个问题。

1)我的页面标题不起作用,而是在浏览器标题栏中显示的是“ myHtml.html”。只有当我宣布script退出时,标题才有效。

2)我希望JavaScript生成的文本是蓝色的,有没有办法做到这一点?

HTML:

<!DOCTYPE html>
<html>
    <head class = "Header">
        <title>JavaScript Test</title>  
        <meta charset = "UTF-8">
        <link rel = "stylesheet" type = "text/css" href = "myCSS.css" > 
        <script type= text/javascript src= myJavaScript.js></script>
    </head>
<body class = "Body" onload = "testJavaScript()">
<p>
<noscript>
    Your javascript is disabled
</noscript>
</p>
</body>
</html>

JavaScript:

function testJavaScript(){
var message = "You Have Javascript!!";
document.writeln(message);
}

CSS:

@charset "UTF-8";

head.Header{
font-family:sans-serif;
color:green;
}

body.Body{
font-family:sans-serif;
color:blue;
}
4

2 回答 2

4

当您document.writelnonload事件触发后使用时(就像您在示例中使用的那样),整个 DOM 将被删除,因此没有 HTML/CSS 可以为您提供标题或蓝色文本。

要测试您要执行的操作,请执行以下操作:

...
<body class="Body">
<p>
<noscript>
    Your javascript is disabled
</noscript>
<script>
    testJavaScript();
</script>
</p>
...

However, I would recommend you don't use document.writeln at all (unless there is a good reason) and use DOM manipulation methods to include your text (e.g. innerHTML). @Shylo's answer is also an approach to take.

于 2013-08-27T03:31:35.963 回答
0
<!DOCTYPE html>
<html>
  <head class="Header">
    <title>JavaScript Test</title>  
    <meta charset="UTF-8">
    <style type="text/css">
      .Body {
        font-family:            sans-serif;
        color:              blue;
      }
    </style>

    <script type="text/javascript">
      window.onload = function() {
        message =           document.createElement('P');
        message.className = "Body";
        message.innerHTML = "You Have Javascript!!";
        document.body.appendChild(message);
      }
    </script>
  </head>


  <body>
    <p>
      <noscript>
        Your javascript is disabled
      </noscript>
    </p>
  </body>
</html>
于 2013-08-27T03:26:44.993 回答