我在1 html 1 css和1 js中转换1个html文件时遇到问题可以让一个人帮忙吗?

时间:2015-03-28 21:31:37

标签: javascript html css

所以我开始编码,但我想我是愚蠢的,因为我已经能够分割这些代码,我很感激一些帮助

<html>
<head>
<title>Exploring HTML</title>
<style>
body {
color: red;
}
h1 {
font-family: Arial, sans-serif;
font-size: 32px;
color: black;
}
</style>
</head>
<body>
<h1>My first web page</h1>
<p>This is my first web page, it's a little basic, but it's helping me understand how HTML works and how to markup my content.</p>
<button id="color">Change color!</button>
<script src="js.js">

</script>
</body>
</html>

2 个答案:

答案 0 :(得分:3)

这是您可以将网页拆分为不同文件的方法。您希望在head标记中使用link来包含外部CSS文件。对于外部script文件,您仍然使用<script>代码但未向其插入任何内容,则应用src属性。 <script>标记可以位于标题中,也可以放在body标记中,通常最好将其添加到body标记的末尾以防止渲染阻止。

<强>的index.html

<html>
<head>
   <title>Exploring HTML</title>
   <link rel="stylesheet" href="style.css" />
</head>
<body>
   <!-- Body Content -->
   <div id="color">Click Here to Rotate Colors</div>
   <script src="script.js"></script>
</body>
</html>

<强>的style.css

body {
   color: red;
}
h1 {
   font-family: Arial, sans-serif;
   font-size: 32px;
   color: black;
}

<强>的script.js

(function() {
   // Set the variable "node" and set the event listener on click
   var node = document.getElementById('color');
   node.addEventListener('click',changeColor,false);

   function changeColor(e) {
      // Get the target (node) that the user clicked
      var target = e.target || e.srcElement;

      // Get the color from the data-color attribute
      var color = target.getAttribute('data-color');

      // Define the colors to rotate
      var colors = ['red','green','blue'];

      // Get the position of the color. red = 0, green = 1, etc
      var index = colors.indexOf(color);

      // If the index is the last item in the array you want
      // to change the index to 0 otherwise it increases by 1
      var next = (index+1 == colors.length ? 0 : index+1);

      // Set the new color and the data-color attribute
      target.style.color = colors[next];
      target.setAttribute('data-color',colors[next]);   
   }
})();

可以在JSFiddle找到上述代码的工作示例。我设置data-color而不是阅读style.color变量的原因是因为我不确定某些浏览器是否可能以不同方式修改此值。我知道浏览器不会修改data-color属性。

答案 1 :(得分:0)