Javascript 更改类的样式css
以下是我代码的一部分: 我们的想法是使用“navicon”类更改两个字段的背景色,就像您在函数fu()中看到的那样,但它不起作用,也不以这种或那种方式起作用。更改id的颜色没有问题,但我不想给任何按钮一个特定的id。知道我的错误和误解在哪里吗?谢谢Javascript 更改类的样式css,javascript,html,css,Javascript,Html,Css,以下是我代码的一部分: 我们的想法是使用“navicon”类更改两个字段的背景色,就像您在函数fu()中看到的那样,但它不起作用,也不以这种或那种方式起作用。更改id的颜色没有问题,但我不想给任何按钮一个特定的id。知道我的错误和误解在哪里吗?谢谢 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <! <link rel="stylesh
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<! <link rel="stylesheet" href="css/navside.css" type="text/css">
<style>
.navside {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333;
}
.navside a {
float: center;
display: block;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
}
.navside a:hover {
background-color: #ddd;
color: black;
}
</style>
</head>
<body>
<script>
function fun(){
document.getElementById("demo").style.backgroundColor="red";
function fu(){
var all = document.getElementsByClassName('navicon');
for(var i=0;i<all.length;i++){
all[i].style.backgroundColor='red';
}
}
}
</script>
<div class="navside">
<a class="navicon" id="demo" href="#bla" onclick="fun()" >Text1</a><br>
<a class="navicon" href="#blubb" onclick="fu()">Text2</a>
</div>
</body>
</html>
navside先生{
列表样式类型:无;
保证金:0;
填充:0;
溢出:隐藏;
背景色:#333;
}
.导航a{
浮动:中心;
显示:块;
颜色:#F2F2;
文本对齐:居中;
填充:14px 16px;
文字装饰:无;
字号:17px;
}
.导航a:悬停{
背景色:#ddd;
颜色:黑色;
}
函数fun(){
document.getElementById(“demo”).style.backgroundColor=“红色”;
函数fu(){
var all=document.getElementsByClassName('navicon');
对于(var i=0;i
问题是您将fu()
的定义放在fun()
中,因此它不能从全局范围调用。它似乎不需要是局部函数,我想这只是一个错误。请全局定义它们
function fun(){
document.getElementById("demo").style.backgroundColor="red";
}
function fu(){
var all = document.getElementsByClassName('navicon');
for(var i=0;i<all.length;i++){
all[i].style.backgroundColor='red';
}
}
函数fun(){
document.getElementById(“demo”).style.backgroundColor=“红色”;
}
函数fu(){
var all=document.getElementsByClassName('navicon');
对于(var i=0;i您正在调用一个不存在的函数
这是正确的:
在lopp中获取长度是一种糟糕的做法
函数fun(){
document.getElementById(“demo”).style.backgroundColor=“红色”;
}
函数fu(){
var all=document.getElementsByClassName('navicon'),
len=所有长度,
我
对于(i=0;i
使用querySelectorAll
可以在没有for循环的情况下实现
function fu(){
document.querySelectorAll('.navicon')
.forEach((el) => { el.style.backgroundColor='red' });
}
您有一个语法错误第5行,您不应该有there.function fun()缺失和结尾“}”…但它不起作用“好的,所以背景色不改变”并且不起作用“What is“this”?“What”way“@vabii the ending”
就在
的正上方。因为我修复了缩进,所以更容易看到。是的,它也按照我想要的方式工作,thx。但是如果我有100个缩进,有没有办法从像el[24]这样的向量中编辑一个缩进…你知道吗?天哪…我用Fortran和C编码了这么多年,然后我犯了这样一个&%§?#*&错误…我->转角->哭->哭得很大声xddthx很多,我看到了,这么愚蠢的错误xD用Fortran和C编码了这么多年,然后又犯了这样一个错误,天哪,真为我感到羞耻xD.Thx寻求帮助
function fun(){
document.getElementById("demo").style.backgroundColor="red";
}
function fu(){
document.querySelectorAll('.navicon')
.forEach((el) => { el.style.backgroundColor='red' });
}