我想用 javascript 实现一些东西,比如当我点击任何缩略图(btn-1、btn-2 和 btn-3)时,特定类应该动态添加到框 div。
我的代码:JSFiddle
document.getElementById('btn-1').onclick = function() {
document.getElementById('box').className = 'bg-1';
}
#box {
background-color: darkgray;
width: 200px;
height: 200px;
}
.thumbnail {
width: 30px;
height: 30px;
border: 1px solid;
margin: 5px;
position: relative;
float: left;
}
#btn-1 {
background-color: red;
}
#btn-2 {
background-color: green;
}
#btn-3 {
background-color: blue;
}
.bg-1 {
background-color: red;
}
.bg-2 {
background-color: blue;
}
.bg-3 {
background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box"></div>
<div class="thumbnail" id="btn-1"></div>
<div class="thumbnail" id="btn-2"></div>
<div class="thumbnail" id="btn-3"></div>
最佳答案
你的 javascript 可以工作,但你的 CSS 不行。
您需要在.bg-1、.bg-2 和.bg-3 中添加如下!important
.bg-1 {
background-color: red !important;
}
否则 id 样式优先于类样式
如果您右键单击灰色的 div 并在 Chrome 中选择检查元素,您可以看到正在添加类名。
关于javascript - 使用javascript onclick将类名添加到div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45871662/