Как применить кастомный стиль CSS к элементу SVG
Я работаю с элементом svg
var defsElement = document.querySelector('defs');
var defsElementX = defsElement.getBBox().x;
var defsElementY = defsElement.getBBox().y;
var colX = [];
for (var i = 0; i < 3; i++) {
(i == 0) ? colX.push(25): colX.push(colX[i - 1] + 60)
};
//console.log(colX);
const y = 145;
const svg = document.querySelector("svg");
const svgns = "http://www.w3.org/2000/svg"
colX.forEach(
(a, i) => {
let useEl = document.createElementNS(svgns, 'use');
useEl.setAttributeNS('http://www.w3.org/1999/xlink', "xlink:href", "#stick man");
useEl.setAttribute("class", "use" + [i]);
useEl.setAttribute("id", "id" + [i]);
useEl.setAttribute("x", `${a}`);
useEl.setAttribute("y", `${y}`);
svg.appendChild(useEl);
}
)
.stickman {
stroke: red;
fill: none;
}
.stickman>.head {
fill: black;
stroke: blue;
}
.head {
fill: brown;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<link rel="stylesheet" href="style.css"></link>
<svg id="layer" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 500 500">
<defs>
<g id="stick man" style="fill: none; stroke: black;">
<circle class="head" cx="10" cy="10" r="10"/>
<line class="body" x1="10" y1="20" x2="10" y2="44"/>
<polyline class="upper" points="1 58, 10 44, 19 58"/>
<polyline class="lower" points="1 24, 10 30, 19 24"/>
</g>
</defs>
<g class="stickman" id="stickman" transform = "translate (85,50)">
<circle class="head" cx="10" cy="10" r="10"/>
<line class="body" x1="10" y1="20" x2="10" y2="44"/>
<polyline class="upper" points="1 58, 10 44, 19 58"/>
<polyline class="lower" points="1 24, 10 30, 19 24"/>
<script href="index.js"></script>
</svg>
</body>
</html>
Я хочу научиться применять стили CSS к другому элементу <use></use>.
Например, как я могу применить 3 разных цвета для заливки каждой головы.
Какой селектор CSS следует использовать?
я пытался так:
.use0>.head {
fill: brown;
}
JavaScript генерирует это:
Свободный перевод вопроса How to apply custom CSS style on SVG element от участника @smpa01.
Ответы (2 шт):
Для этого вы можете использовать переменные CSS:
const svg = document.querySelector("svg");
const svgns = "http://www.w3.org/2000/svg";
for (let i = 0; i < 3; ++i) {
let useEl = document.createElementNS(svgns, 'use');
useEl.setAttributeNS('http://www.w3.org/1999/xlink', "xlink:href", "#stickRef");
useEl.setAttribute("id", `id${i}`);
useEl.setAttribute("x", (i * 60) + 25);
useEl.setAttribute("y", 25);
svg.appendChild(useEl);
}
#id0 { --head-colour: #F00; --line-colour: #900; }
#id1 { --head-colour: #0F0; --line-colour: #090; }
#id2 { --head-colour: #00F; --line-colour: #009; }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 500 500">
<defs>
<symbol id="stickRef" style="fill: none; stroke: var(--line-colour);">
<circle class="head" cx="10" cy="10" r="10" style="fill: var(--head-colour)" />
<line class="body" x1="10" y1="20" x2="10" y2="44"/>
<polyline class="upper" points="1 58, 10 44, 19 58"/>
<polyline class="lower" points="1 24, 10 30, 19 24"/>
</symbol>
</defs>
</svg>
Свободный перевод ответа от участника @Mike D Sutton.
Вы можете обернуть группу с помощью <g> и присвоить группе style="fill: none;" - закраска только линии и <polyline> человечка-палки, оставляя круг с неопределенной заливкой.
Теперь вы можете установить атрибут заливки или придать стиль элементу <use>. Заливка будет применена только к кругу.
use{fill:red}
use:nth-of-type(2){fill:gold}
use:nth-of-type(3){fill:blue}
<svg id="layer" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 100 500 500">
<defs>
<g id="stickman" style="stroke: black;">
<circle class="head" cx="10" cy="10" r="10"></circle>
<g style="fill: none;">
<line class="body" x1="10" y1="20" x2="10" y2="44"></line>
<polyline class="upper" points="1 58, 10 44, 19 58"></polyline>
<polyline class="lower" points="1 24, 10 30, 19 24"></polyline>
</g>
</g>
</defs>
<use xlink:href="#stickman" x="25" y="145"></use>
<use xlink:href="#stickman" x="85" y="145"></use>
<use xlink:href="#stickman" x="145" y="145"></use>
</svg>
