[英]Adding svg rectangles to checkboxes dynamically
我正在嘗試在列表的每個復選框的左側添加一個彩色矩形,該矩形由d3.js使用以下代碼自動創建:
d3.selectAll("#checkbox")
.selectAll("label")
.data(dataset, function (d) { return d.Grazie; })
.enter()
.append("div")
.attr("id", function (d) { return d.Grazie; })
.append("label")
.attr("class", "label")
.attr("id", function (d) { return d.Grazie; })
.text(function (d) { return d.Grazie; })
.append("input")
.attr({
type: "checkbox",
class: "Grazie",
name: "mode",
value: function (d, i) { return d.Grazie; }
})
.attr("id", function (d, i) { return d.Grazie; })
.attr("x", margin)
.attr("y", margin)
.attr("selected", null);
我嘗試在此過程之后附加一個svg和一個矩形,但是得到的是,使用以下代碼將該矩形放置在文本和復選框之后:
d3.select("#checkbox")
.select("#Sans")
.append("svg")
.attr("width", 8 + "px")
.attr("height", 8 + "px")
.append("rect")
.attr("fill", function (d) {
if (d.Grazie == "Sans") { return "#386cb0"; }
else { return "#f0027f"}})
.attr("x", 0)
.attr("y", 0)
.attr("width", 8 + "px")
.attr("height", 8 + "px");
我想要的順序是:
矩形-文字-復選框
我猜想矩形的代碼可以在創建復選框時集成,但是無法使其正常工作。 非常感謝您的任何幫助,謝謝!
您應該這樣分解:
var entries = d3.select("#checkbox") // select is more appropriate than selectAll
.selectAll("div.list-entry")
.data(dataset, function (d) { return d.Grazie; })
var newEntries = entries.enter() // newEntries holds the result of .enter()
.append("div")
.attr("id", function (d) { return d.Grazie; })
.attr("class", "list-entry")
newEntries // now you can append various stuff into each div in newEntries
.append("label")
.attr("class", "label")
.attr("id", function (d) { return d.Grazie; })
.text(function (d) { return d.Grazie; })
newEntries
.append("input")
.attr({
type: "checkbox",
class: "Grazie",
name: "mode",
value: function (d, i) { return d.Grazie; }
})
.attr("id", function (d, i) { return d.Grazie; })
.attr("x", margin)
.attr("y", margin)
.attr("selected", null);
然后,您可以在標簽創建代碼之前插入矩形創建代碼(遵循用於標簽和輸入創建的相同模式)。
但是...為什么要使用<svg>
和<rect>
來制作一個簡單的矩形? 太復雜了。 為什么不只使用具有CSS寬度,高度,背景顏色和display:inline-block
或float:left
的普通<div>
?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.