如何解决setAttribute HTML 后不显示多边形
我想在我的 html 代码中动态创建一个三角形,我以后想修改和使用它。 但是从一开始就没有出现。
onclick 函数正确触发,新对象出现在 html 中,但该对象无处可见。
function start_dreiecke() {
var xmlns = "http://www.w3.org/2000/svg";
var svg = document.createElementNS(xmlns,"svg");
var polygon = document.createElementNS(xmlns,"polygon");
polygon.setAttribute('id','triangle_' + '01');
polygon.setAttribute('style','width:200px;height:200px;');
polygon.setAttribute('points','1000,779 100,779 550,0');
polygon.setAttribute("style","fill:yellow;stroke:yellow;stroke-width:1;fill-rule:nonzero;");
svg.appendChild(polygon);
document.getElementById('canvas').appendChild(svg);
}
#canvas
{
position: absolute;
width: 100px;
height:100px;
}
svg
{
position:absolute;
height:100px;
width:100px;
}
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script src="https://d3js.org/d3.v5.min.js" charset="utf-8"></script>
<h1>Schnittstellendreieck</h1>
<p>Hier ist eine Baustelle für bessere Baustellen.</p>
<!-- Hier werden die Dreiecke generiert. -->
<div id="button">
<h2 onclick="start_dreiecke()">Start Dreieck</h2>
</div>
<canvas id="canvas"></canvas>
<h3 id="clicked"></h3>
为什么我的三角形不显示?
解决方法
canvas
HTML 元素不应该有子元素。这是一种白板,其中线条和形状没有任何 DOM 表示。另一方面,svg
具有 DOM 表示,因此只需删除 canvas
并将 svg
附加到 DOM 中的其他位置。
function start_dreiecke() {
var xmlns = "http://www.w3.org/2000/svg";
var svg = document.createElementNS(xmlns,"svg");
var polygon = document.createElementNS(xmlns,"polygon");
polygon.setAttribute('id','triangle_' + '01');
polygon.setAttribute('style','width:200px;height:200px;');
polygon.setAttribute('points','1000,779 100,779 550,0');
polygon.setAttribute("style","fill:yellow;stroke:yellow;stroke-width:1;fill-rule:nonzero;");
svg.appendChild(polygon);
document.body.appendChild(svg);
}
#canvas
{
position: absolute;
width: 100px;
height:100px;
}
svg
{
position:absolute;
height:500px;
width:500px;
}
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script src="https://d3js.org/d3.v5.min.js" charset="utf-8"></script>
<h1>Schnittstellendreieck</h1>
<p>Hier ist eine Baustelle für bessere Baustellen.</p>
<!-- Hier werden die Dreiecke generiert. -->
<button onclick="start_dreiecke()" id="button">Start Dreieck</button>
<h3 id="clicked"></h3>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。