我有一些 jquery 将 SVG 附加到类为 .fade-top-onbottom
的任何 div,然后使用 CSS 变量设置 SVG 渐变的样式。 css 变量适用于页面上的第一个 SVG,但不适用于其他。
这是由于linearGradient中的#fadeDown。如果我设置一个唯一的#,它就可以工作(这是有道理的)。
我怎样才能让 jQuery 为每个附加的渐变插入一个唯一的 ID?
$(".fade-top-onbottom").append("<div class='dh-bottom-divider-fade-top'><svg width='100%' height='100%' viewBox='0 0 1280 140' preserveAspectRatio='none' xmlns='http://www.w3.org/2000/svg'><defs><linearGradient id='fadeDown' x1='0' x2='0' y1='0' y2='1'><stop offset='0%' stop-color='var(--bottom-divider-color, #999)'/><stop offset='100%' stop-color='var(--bottom-divider-color, #999)' stop-opacity='0'/></linearGradient></defs><path d='M 0 0 L 0 140 L 1280 140 L 1280 0 Z' fill='url(#fadeDown)'/></svg></div>");
body {
background:#000;
height:100%;
width:100%;
}
.yellow {
--bottom-divider-color:yellow;
}
.red {
--bottom-divider-color:red;
}
.blue {
--bottom-divider-color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='fade-top-onbottom yellow'></div>
<div class='fade-top-onbottom red'></div>
<div class='fade-top-onbottom blue'></div>
最佳答案
您可以遍历元素并为每个 id
添加索引。
var gradients = $(".fade-top-onbottom");
gradients.each(function(index) {
$(this).append("<div class='dh-bottom-divider-fade-top'><svg width='100%' height='100%' viewBox='0 0 1280 140' preserveAspectRatio='none' xmlns='http://www.w3.org/2000/svg'><defs><linearGradient id='fadeDown" + index + "' x1='0' x2='0' y1='0' y2='1'><stop offset='0%' stop-color='var(--bottom-divider-color, #999)'/><stop offset='100%' stop-color='var(--bottom-divider-color, #999)' stop-opacity='0'/></linearGradient></defs><path d='M 0 0 L 0 140 L 1280 140 L 1280 0 Z' fill='url(#fadeDown" + index + ")'/></svg></div>");
});
body {
background:#000;
}
.yellow {
--bottom-divider-color:yellow;
}
.red {
--bottom-divider-color:red;
}
.blue {
--bottom-divider-color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='fade-top-onbottom yellow'></div>
<div class='fade-top-onbottom red'></div>
<div class='fade-top-onbottom blue'></div>
关于jquery - CSS 变量不适用于多个 SVG 渐变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52451873/