我正在着手构建自己的动态 Accordion ,我希望每个选项卡看起来都像图像。例如,每个都可以是带有 div 子项或列表的标题标签。
Accordion 将是动态的,用户可以随意添加更多标签。顶层将是同级元素,它们将具有下拉列表的子元素(也是动态的)。
我一直没能找到一种解决方案来从第一个开始对每个兄弟顺序迭代颜色并在迭代时淡化或变亮颜色?
构建我自己的 Accordion 的想法是让它尽可能轻,所以需要考虑这一点。任何人都可以指出我正确的方向吗?
编辑 试图添加代码笔,但它不会让我。请参阅下面我的评论以获取链接。
最佳答案
使用 Jquery 我的方法是这样的:
//First start with a string to store the color whitout alpha
var color="rgba(180,125,255,";
function repaint() {
//Know how many tabs you have and which is the % increment you need
var all = $('.tab').length,
total = 10/all;
//Iterate over all elements and set the new color based on Index
$('.tab').each(function(i){
var opacity = (total*(all-i))/10,
newTone = color+opacity+")";
$(this).css('background-color',newTone)
})
}
repaint()
Codepen Demo
您还有很多方法可以改进此代码,例如简化颜色输入以接受 HEX 和其他值。
片段演示
var color = "rgba(180,125,255,";
function repaint() {
var all = $('.tab').length,
total = 10 / all;
$('.tab').each(function(i) {
var opacity = (total * (all - i)) / 10,
newTone = color + opacity + ")";
$(this).css('background-color', newTone)
})
}
repaint()
$('button').on('click', function(e) {
e.preventDefault();
$('body').append('<div class="tab"></div>')
repaint()
})
.tab {
height: 40px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Add Tab</button>
<div class="tab"></div>
<div class="tab"></div>
<div class="tab"></div>
关于jquery - 使用 css/scss 或 js 动态实现颜色效果不透明度/渐变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43259381/