我試圖解決的問題如下:
我創建了一個 500x500 像素的 svg。在這個 svg 中,我附加了一個半徑為 50px 的圓。我在圓圈上添加了一個點擊事件,使其顏色變為紅色。我在 svg 的其余部分添加了一個點擊事件,以便圓圈的顏色變為綠色。
這可能嗎?
我試圖將點擊事件放在 svg 上,它覆寫了整個 500x500 像素,阻止了附加到圓圈的點擊事件作業。
有人暗示我使用 stopPropagation,但使用它沒有成功。
var svg = d3.select("#cv")
.attr("height", 300)
.attr("width", 300)
.style("border", "1px solid red")
.on("click", function(d) {
circ.style("fill", "green")
});
var circ = svg
.append("circle")
.attr("r", 100)
.attr("cx", 100)
.attr("cy", 100)
.attr("stroke", "black")
.style("fill", "grey")
.on("click", function(d) {
circ.style("fill", "red")
});
#cv {
width: 300px;
}
<script src="https://d3js.org/d3.v5.min.js"></script>
<svg id="cv">
<defs>
<pattern id="image" x="0" y="0" patternUnits="userSpaceOnUse" height="200" width="200">
<image x="0" y="0" href="https://i.stack.imgur.com/skwGx.jpg" width="200" height="200"></image>
</pattern>
</defs>
</svg>
uj5u.com熱心網友回復:
您可以為此使用一個技巧:附加一個rect與 SVG 尺寸相同的白色角度,并向其添加點擊偵聽器。確保首先添加它,因為 SVG 沒有z-index,而是通過在所有以前的專案上繪制每個專案來作業。所以你定義的第一個專案本質上是背景。
var svg = d3.select("#cv")
.attr("height", 300)
.attr("width", 300)
.style("border", "1px solid red");
var bg = svg.append("rect")
.attr("width", 300)
.attr("height", 300)
.attr("fill", "white")
.on("click", function(d) {
circ.style("fill", "green")
});
var circ = svg
.append("circle")
.attr("r", 100)
.attr("cx", 100)
.attr("cy", 100)
.attr("stroke", "black")
.style("fill", "grey")
.on("click", function(d) {
circ.style("fill", "red")
});
#cv {
width: 300px;
}
<script src="https://d3js.org/d3.v5.min.js"></script>
<svg id="cv">
<defs>
<pattern id="image" x="0" y="0" patternUnits="userSpaceOnUse" height="200" width="200">
<image x="0" y="0" href="https://i.stack.imgur.com/skwGx.jpg" width="200" height="200"></image>
</pattern>
</defs>
</svg>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/377330.html
