所以我开始编码,但我想我是愚蠢的,因为我已经能够分割这些代码,我很感激一些帮助
<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>
答案 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)