gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 16:09:54 25 4
gpt4 key购买 nike

所以我已经开始编码,但我想我很笨,因为我无法拆分这段代码,我希望得到一些帮助

<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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com