gpt4 book ai didi

javascript - 定位由 d3.js 创建的 div

转载 作者:太空宇宙 更新时间:2023-11-04 02:32:19 24 4
gpt4 key购买 nike

我有四个由 d3 创建的 div。我希望每行出现 2 个 div。我想考虑 div 的宽度和高度。基本上一行会有 2 个 div,如果一行中的一个 div 有一定的高度,那么从那个 div 的底部到顶部下方的 div 应该总是有 20px 的间隙。我希望行上第一个 div 的左侧到第二个 div 的右侧有 20px 的间隙

我有这样的数据对象:

    var data = [
{"name" : "alpha", "desc" : "This is Alpha"},
{"name" : "Beta", "desc" : "This is Beta"},
{"name" : "Gama", "desc" : "This is Gama"},
{"name" : "Delta", "desc" : "This is Delta"},

]

我希望把它做成这样:

    {"name" : "alpha", "desc" : "This is Alpha", "top" : 0, "left"  : 0,"width" : 200, "height" : 300 },
{"name" : "Beta", "desc" : "This is Beta", "top" : 0, "left" : 220,"width" : 200, "height" : 300},
{"name" : "Gama", "desc" : "This is Gama", "top" : 320, "left" : 0,"width" : 250, "height" : 350},
{"name" : "Delta", "desc" : "This is Delta", "top" : 320, "left" : 270,"width" : 250, "height" : 350},

我正在尝试将尺寸添加到 obj 中,以便我可以轻松地使用 .style 并插入适当的值。像这样。style("left", function(d){return d.left)。如果您有其他解决方案,我会很乐意提供。我愿意使用 jQuery。

由于绝对位置,我的代码只显示 Angular 落的 div。

var data = [
{"name" : "alpha", "desc" : "This is Alpha"},
{"name" : "Beta", "desc" : "This is Beta"},
{"name" : "Gama", "desc" : "This is Gama"},
{"name" : "Delta", "desc" : "This is Delta"}

]

d3.selectAll("div.store")
.data(data)
.enter()
.append("div")
.classed("store", true)
.html( function(d){return "<h1 class = 'name'>"+ d.name + "</h1> <p class = 'desc'>" + d.desc + "</p>"})
.style("position" , "absolute")

var dim = d3.selectAll("div.store")
.node().getBoundingClientRect()

console.log(dim.width)
.name{
color: steelblue;
}
.store {
width : 200px;
border: 1px solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>

最佳答案

您已经非常接近目标了。您所要做的就是设置 topleft 样式属性。

var data = [
{"name": "alpha", "desc": "This is Alpha", "top": 0, "left": 0, "width": 200, "height": 300},
{"name": "Beta", "desc": "This is Beta", "top": 0, "left": 220, "width": 200, "height": 300},
{"name": "Gama", "desc": "This is Gama", "top": 320, "left": 0, "width": 250, "height": 350},
{"name": "Delta", "desc": "This is Delta", "top": 320, "left": 270, "width": 250, "height": 350}
];

d3.selectAll('div.store')
.data(data)
.enter().append('div')
.attr('class', 'store')
.html(function(d) { return "<h1 class = 'name'>" + d.name + "</h1> <p class = 'desc'>" + d.desc + "</p>"; })
.style('position', 'absolute')
.style('top', function(d) { return d.top + 'px'; })
.style('left', function(d) { return d.left + 'px'; })
.style('height', function(d) { return d.height + 'px'; })
.style('width', function(d) { return d.width + 'px'; });
.name {
color: steelblue;
}
.store {
border: 1px solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>

关于javascript - 定位由 d3.js 创建的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36289797/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com