再加上javascript
时间: 2023-08-15 15:03:25 浏览: 53
好的,下面是一个包含 JavaScript 的示例代码,展示如何使用 JavaScript 对前面的 HTML 和 CSS 代码进行交互和操作:
```html
<!DOCTYPE html>
<html>
<head>
<title>My First Frontend Code</title>
<style>
h1 {
color: blue;
text-align: center;
}
p {
font-size: 18px;
line-height: 1.5;
margin-bottom: 20px;
}
ul {
list-style: none;
margin: 0;
padding: 0;
}
li {
margin-bottom: 10px;
}
.btn {
display: block;
width: 100px;
height: 30px;
background-color: green;
color: white;
text-align: center;
line-height: 30px;
border-radius: 5px;
margin-top: 20px;
cursor: pointer;
}
</style>
</head>
<body>
<h1>Welcome to my website!</h1>
<p>This is a paragraph of text.</p>
<ul>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ul>
<button class="btn" onclick="changeText()">Change Text</button>
<script>
function changeText() {
var text = document.querySelector("p");
text.innerHTML = "The text has been changed!";
}
</script>
</body>
</html>
```
在这个示例中,我们在 `<body>` 元素的底部添加了一个按钮元素,并为其定义了一个名为 `.btn` 的 CSS 类,该类定义了按钮的样式。我们在按钮元素上添加了一个 `onclick` 事件处理程序,当单击按钮时,将调用名为 `changeText()` 的 JavaScript 函数。该函数使用 `document.querySelector()` 方法选择页面中的 `<p>` 元素,并将其文本内容更改为“文本已更改!”。我们可以看到,JavaScript 代码可以与 HTML 和 CSS 代码进行交互和操作,从而使页面具有更多的交互性和动态性。
这样,当您将此代码复制并粘贴到文本编辑器中,并将其保存为 `.html` 文件,然后在浏览器中打开该文件,您将看到一个带有样式和交互功能的简单网页。