2017-04-21 73 views
1

我有一个问题与javascript.I想要控制jumbotron的颜色,并将其设置为每3秒随机one.The问题在于,我不知道如何操作JavaScript与JavaScript,因为我对JavaScript很新颖。我看到一些其他的解决方案和一些其他的线程,但它不起作用(我不知道我是否做错了什么)。 我现在没有写js代码,因为我删除了一切无法使用的东西。使用Javascript的jumbotron颜色处理

.jumbotron { 
    background-color: #f14444 !important; 
} 
/*Without the !important rule it won't change color!*/ 

如果你有,你认为我没有检查我会很乐意进行检查,但即时通讯有足够的信心说,我见过他们已经任何线程。
无论如何感谢您的时间!

+0

有很多对这里良好的信息:https://开头www.w3.org/wiki/Dynamic_style_-_manipulating_CSS_with_JavaScript – AdjunctProfessorFalcon

+0

[小提琴,如何使用CSS va一次改变整个文档中多个节点的颜色,而不是连接节点的颜色rs](https://jsfiddle.net/xg7vzpfy/) – Thomas

回答

1

要更改背景颜色,只需选择元素和设置属性:

setTimeout(() => { 
 
    document.querySelector('.jumbotron').style.backgroundColor = '#f14444'; 
 
}, 1000);
.jumbotron { 
 
    height: 300px; 
 
    width: 300px; 
 
    background-color: black; 
 
}
<div class="jumbotron"></div>

注意,上面会选择给定类的第一个找到的元素,因此,如果您需要针对特定​​元素,请考虑给它一个id并将其选为@Phil在上面显示。

+1

非常感谢! –

+0

你是weocome! @AlexPyrg – baao

1

DOM中的HTML元素具有style属性。

document.getElementById('something').style.backgroundColor = '#ccc' 

注意,像CSS background-color复姓性能通常是驼峰(的backgroundColor)在Javascript。

1

你也可以用keyframe animation

这里实现它是一个tutorial如何获得随机颜色

@-webkit-keyframes changeColors { 
 
    0% { 
 
    background-color: red; 
 
    } 
 
    50% { 
 
    background-color: blue; 
 
    } 
 
    100% { 
 
    background-color: green; 
 
    } 
 
} 
 

 
@-moz-keyframes changeColors { 
 
    0% { 
 
    background-color: red; 
 
    } 
 
    50% { 
 
    background-color: blue; 
 
    } 
 
    100% { 
 
    background-color: green; 
 
    } 
 
} 
 

 
@-ms-keyframes changeColors { 
 
    0% { 
 
    background-color: red; 
 
    } 
 
    50% { 
 
    background-color: blue; 
 
    } 
 
    100% { 
 
    background-color: green; 
 
    } 
 
} 
 

 
.jumbotron { 
 
    -webkit-animation: changeColors 3s infinite; 
 
    -moz-animation: changeColors 3s infinite; 
 
    -ms-animation: changeColors 3s infinite; 
 
    background-color: #f14444; 
 
}
<div class="jumbotron"> 
 
    Some text here 
 
</div>