javascript - 如何让 onclick 事件用于更改 CSS 属性?
问题描述
我是尝试 Javascript 的初学者。我想通过 onclick 事件更改字体颜色和字体系列(以及背景图像的渐变,但我什至无法猜测如何访问它)。我制作了一个按钮,单击该按钮应运行 spookFunction 并将正文中的字体颜色更改为橙色,将字体系列更改为谷歌字体 Bangers。我试图为您制作一个小提琴以查看代码(这是我第一次使用 JSFiddle,所以我不确定它是如何工作的): https ://jsfiddle.net/Linnea_Borealis/u8n9ezhs/10/ 我剪辑在一个我发现一些示例代码只是为了看看它是否可以工作并与我自己的代码进行比较:
单击我以更改我的文本颜色。 <script>
function myFunction() {
document.getElementById("demo").style.color = "red";
}
</script>
那部分工作正常,但另一部分没有。有什么不同?
我注意到在 VS Code 中,“style”在“document.getElementById("welcome").style.color="red"" 中比在 "document.getElementsByTagName("body").style.color="orange" 中具有另一种颜色;" 和 "document.getElementsByTagName("body").style.fontFamily="Bangers", cursive;" 我是否以错误的方式使用 getElementsByTagName?
此外,在 JS Fiddle 中,文本周围有一个白色矩形,当我在浏览器中打开 html 文件时看不到它......为什么?如果有人能以对初学者友好的方式解释这一点,我将非常感激。
解决方案
白色矩形是你的身体。如果您添加您的 css 正文类background-color:black;
,您可以看到它。关于 getElementsByTagName 的其他答案是正确的。
尝试这个:
function myFunction() {
document.getElementById("demo").style.color = "red";
}
function spookFunction() {
document.getElementsByTagName("body")[0].style.color="orange";
document.getElementsByTagName("body")[0].style.fontFamily="Bangers, cursive";
document.getElementById("welcome").style.color="red"
}
html {
background-image: linear-gradient(#0099ff, white);
min-height: 100%;
}
body {
margin-left: 10%;
margin-right: 10%;
margin-top: 10%;
font-family: 'Lobster', cursive;
color: white;
background-color: black;
}
h1{ font-size: 50px; }
p {
font-size: 30px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Spook My Page</title>
<link rel="stylesheet" type="text/css" href="Style.css">
<link href="https://fonts.googleapis.com/css2?family=Bangers&family=Lobster&display=swap"
rel="stylesheet">
</head>
<body>
<h1 id="welcome">Welcome Friend!</h1>
<p>To change the color scheme — Click the button below!</p>
<p id="demo" onclick="myFunction()">Click me to change my text color.</p>
<button type="button" onclick="spookFunction()">Click Me!
</button>
</body>
</html>
推荐阅读
- javascript - 具有随机效果的图像滑块
- python - Pygame - 无法将图像绘制到屏幕:TypeError:draw()缺少1个必需的位置参数:'surface'
- image - Xamarin.Forms iOS 图像未显示
- git - git log --since 不包括预期的提交
- amazon-web-services - 如何使用 AWS 在 React Native 中发送“您有一段时间没有使用您的应用程序”的推送通知?
- c# - 如何使用 ImageUrl 属性?
- python - 在 Robotframework 中编码问题打印字典
- git - Github UI 合并的 3 种类型的细分
- arrays - PHP - 在特定数组值中搜索
- process - 操作系统如何管理进程