我有两个六边形 div。我通过一些 jQuery 搞乱了自己的方式来创建一个函数,该函数将从两种颜色中随机选择来决定 div 的背景颜色。问题是,我还希望六边形的顶部和底部边框更改为其主体的相应颜色。我正在使用 :before 和 :after 伪元素来创建我的六边形,但无法将我的函数应用于它们。任何帮助将不胜感激!
$(document).ready(function() {
var randomColors = ["#96281B","#F7CA18"];
$(".hexagon").each(function(index) {
var len = randomColors.length;
var randomNum = Math.floor(Math.random()*len);
$(this).css("backgroundColor",randomColors[randomNum]);
});
});
这是一个 JSFiddle 来展示我已经拥有的内容:http://jsfiddle.net/k7eo7r1m/
最佳答案
为每种颜色设置 CSS 类名称,然后将适当的类添加到六边形中可能会更容易。
不幸的是,我不相信您可以更改 ':after' 元素的 CSS,因为它们实际上并不存在于 DOM 中,因此您无法访问它。
编辑:这是一个 fiddle
JS:
$(document).ready(function() {
var randomColors = ["","altColor"];
$(".hexagon").each(function(index) {
var len = randomColors.length;
var randomNum = Math.floor(Math.random()*len);
$(this).addClass(randomColors[randomNum]);
});
});
CSS:
.hexagon {
position: relative;
display: inline-block;
width: 100px;
height: 57.74px;
background-color: #F7CA18;
margin: 28.87px 0;
margin-right: 4px;
}
.hexagon:before,
.hexagon:after {
content: "";
position: absolute;
width: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
}
.hexagon:before {
bottom: 100%;
border-bottom: 28.87px solid #F7CA18;
}
.hexagon:after {
top: 100%;
width: 0;
border-top: 28.87px solid #F7CA18;
}
.altColor {
background-color: #96281B;
}
.altColor:before {
border-bottom: 28.87px solid #96281B;
}
.altColor:after {
border-top: 28.87px solid #96281B;
}
EDIT2:我已经清理了 CSS。
关于jquery - 对背景和边框应用相同的随机颜色变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26496839/