我正在尝试使 svg 宽度取决于父母的宽度
为此,我启动了两个变量...并使用它们
100px显示在 console.log 中,这是正确的,应该是这样,但是svg应该是100px * 2,但是出现了NaN我也明白这不是错误,但也不是数字..
如何纠正这种情况?
let item = document.querySelector(".item-svg"),
x = 10,
n = 0,
c = x*2,
vh = x*6,
start = `m ${n} ${n} h${x} v${x}`,
c1 = `c ${n} ${x} ${x} ${x} ${x} ${c}`,
c2 = `c ${n} ${x} ${-x} ${x} ${-x} ${c}`,
finish = `v ${x} h ${-x}`,
con = `${start} ${c1} ${c2} ${finish}`,
svg = document.createElementNS('http://www.w3.org/2000/svg', "svg"),
path = document.createElementNS('http://www.w3.org/2000/svg', "path"),
color = getComputedStyle(item).backgroundColor,
parentWidth = getComputedStyle(item).width;
console.log(parentWidth);
svg.setAttribute("viewBox", `0 0 ${c} ${vh}`);
svg.setAttribute("width", parentWidth*2);
console.log(svg.getAttribute("width"));
path.setAttribute("d", con);
path.setAttribute("fill", color);
svg.append(path);
item.append(svg);
html,body{
margin: 0;
}
.item-svg{
position: relative;
width: 100px;
height: 100vh;
background-color: pink;
}
.item-svg svg{
position: absolute;
left: 0;
}
<div class="item-svg"></div>
关于这个变量: parentWidth = getComputedStyle(item).width;
'100px' 是字符串,不是数字,不能相乘或相加。您需要先将其转换为数字,
+它也不起作用,它只能与写成字符串('100')的数字一起使用。使用parseInt,它可以处理以数字开头的字符串