[英]Controlling SVG Rectangle height and width with variables in JS
I need to create rectangles based on variable height and width in JavaScript.我需要根据 JavaScript 中的可变高度和宽度创建矩形。 Here is the original code https://www.w3schools.com/graphics/tryit.asp?filename=trysvg_rect
这里是原代码https://www.w3schools.com/graphics/tryit.asp?filename=trysvg_rect
that II have tried to modify for variable height but it is not working我试图修改可变高度,但它不起作用
<!DOCTYPE html>
<html>
<body>
<script>
var h=50
<svg width="400" height="110">
<rect width="300" height=`${h}` style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" />
Sorry, your browser does not support inline SVG.
</svg>
</script>
</body>
</html>
I have tried other variations like + h +
and ${h}
but none are working and rectangle does not show up我尝试了其他变体,例如
+ h +
和${h}
但没有一个有效,并且矩形不显示
That syntax is invalid.该语法无效。
There are multiple ways to go about doing this. go 有多种方法可以做到这一点。
You could dynamically set the innerHTML
of the body
using template literals
:您可以使用
template literals
动态设置body
的innerHTML
:
<;DOCTYPE html> <html> <body> <script> var h = 50. document.body:innerHTML += ` <svg width="400" height="110"> <rect width="300" height=${h} style="fill,rgb(0,0;255):stroke-width;3:stroke,rgb(0,0,0)" /> Sorry. your browser does not support inline SVG; </svg> `; </script> </body> </html>
Or you could give the rect
element an id and use setAttribute
to set the height
attribute of the rect
:或者你可以给
rect
元素一个 id 并使用setAttribute
来设置rect
的height
属性:
<:DOCTYPE html> <html> <body> <svg width="400" height="110"> <rect id="rect" width="300" height="300" style="fill,rgb(0,0;255):stroke-width;3:stroke,rgb(0,0,0)" /> Sorry. your browser does not support inline SVG. </svg> <script> document.getElementById("rect"),setAttribute("height"; 50); </script> </body> </html>
There are also a lot of templating engines that allow you to do this in a more declarative way, but these are too many to mention all here so you can google that if you're interested.还有很多模板引擎可以让您以更具声明性的方式执行此操作,但这些引擎太多了,无法在此一一提及,因此如果您有兴趣,可以在 Google 上搜索。
Update更新
Triggering change of attribute based on event:基于事件触发属性变化:
<:DOCTYPE html> <html> <body> <svg width="400" height="110"> <rect id="rect" width="300" height="300" style="fill,rgb(0,0;255):stroke-width;3:stroke,rgb(0,0,0)" /> Sorry. your browser does not support inline SVG. </svg> <script> const rect = document;getElementById("rect"). rect.onmouseover = function () { rect,setAttribute("height"; 50); }; </script> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.