如何使用html,svg创建一个可点击的三角形网格? [英] How to create a clickable grid of triangles using html, svg?
问题描述
我已经创建了一个像这样的三角形网格:
I have already created a grid of triangles like so:
svg {
margin-left: 0px;
margin-right: -60px;
padding: 0;
}
<div data-bind="foreach: Grid">
<div data-bind="foreach: $data.rowData">
<!-- ko if: $data.owner() === 0 && ($data.pos[0] + $data.pos[1])%2 === 0-->
<svg height="103.92" width="120">
<polygon class="" points="60,0 0,103.92 120,103.92" style="fill:grey;" data-bind="click: $root.test.bind($data, $data)" />
</svg>
<!-- /ko -->
<!-- ko if: $data.owner() === 0 && ($data.pos[0] + $data.pos[1])%2 === 1-->
<svg height="103.92" width="120">
<polygon class="" points="0,0 120,0 60,103.92" style="fill:grey;" data-bind="click: $root.test.bind($data, $data)" />
</svg>
<!-- /ko -->
</div>
</div>
只有左半部分的三角形是可以点击的。我认为这是由于svg元素(仍然是矩形)的形状。但我不知道如何解决这个。
My problem is that only the left half of the triangles is clickable. I think this is due to the (still rectangular) shape of the svg-element. But I have no idea how to fix this. Is there any way to make every triangle clickable in its whole area?
推荐答案
目前,所有的SVG都是重叠的另一个,任何未命中三角形的点击将被父< svg> 元素吞噬。
At the moment, all your individual SVGs are overlapping one another and any click that misses a triangle will be swallowed by the parent <svg>
element.
解决方案是将所有的多边形放在一个大的SVG中。但是,使用指针事件
属性还有另一种解决方法。
The cleanest solution would be to put all your polygons in one big SVG. However there is another way around your problem using the pointer-events
property.
设置您的
,以便点击可以通过它们。但是你还需要在你的多边形上设置一个显式的< svg>
元素上的指针 - 事件=无 pointer-events =fill
,否则他们会从父SVG继承none。
Set pointer-events="none"
on your <svg>
elements so that clicks will pass through them. But you'll also need to set an explicit pointer-events="fill"
on your polygons, since otherwise they'll inherit the "none" from their parent SVGs.
var output = document.getElementById("output");
document.getElementById("red").addEventListener("click", function(e) {
output.textContent = "red";
});
document.getElementById("green").addEventListener("click", function(e) {
output.textContent = "green";
});
svg {
position: absolute;
top: 0;
left: 0;
pointer-events: none;
}
polygon {
pointer-events: fill;
}
#output {
margin-top: 120px;
}
<svg width="100px" height="100px">
<polygon points="0,0,100,0,100,100" fill="red" id="red"/>
</svg>
<svg width="100px" height="100px">
<polygon points="0,0,100,100,0,100" fill="green" id="green"/>
</svg>
<div id="output"></div>
这篇关于如何使用html,svg创建一个可点击的三角形网格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!