javascript - 我在将 1 个 html 文件转换为 1 个 html、1 个 css 和 1 个 js 时遇到问题,有人可以帮帮我吗?

标签 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>

最佳答案

这是将网页拆分成不同文件的方法。你想使用 link在 head 标签中包含外部 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>

样式.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属性。

关于javascript - 我在将 1 个 html 文件转换为 1 个 html、1 个 css 和 1 个 js 时遇到问题,有人可以帮帮我吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29322865/

相关文章:

javascript - 将子 div 附加到父 div 的每个实例

javascript - 如何从 Onclick 按钮中获取 ID?

php - 分页 : Highlight Current Number Button

javascript - jcarousel 宽度问题

javascript - 打印 div 内容时占用空间和空白页

javascript - 具有复杂对象的 KnockoutJS 映射插件

javascript - 如何使用 cookie 保存 menu_toggle 的设置?

html - 跨度悬停时填充文字效果

css - 如何删除Concrete5 Tweetcrete中的小鸟图标

尽管有 block 属性,HTML 元素仍然重叠