【问题标题】:Getting a d3 rectangle to span over an entire row让 d3 矩形跨越整行
【发布时间】:2016-05-04 17:18:13
【问题描述】:

目标是有一个显示项目名称和项目百分比的表格。我想放入一个动画背景颜色,以直观地显示这个百分比。因此,如果 % 为 25,则表格行的 25% 将被填充颜色。到目前为止,这就是我所拥有的。我决定制作一个额外的 td 来保存与前两个重叠的矩形。

cshtml(在引导模式中):

            <script>
                var modelThing = @Html.Raw(Json.Encode(Model.Things));
            </script>
            <table id="tableThing">
                <tr>
                    <th>Name</th>
                    <th>%</th>
                </tr>
            </table>

js:

var t = $("table#tableThing");

$.each(modelThing , function (i, thing) {

    t.append('<tr style="position: relative"><td>' + thing.Name + '</td><td>' + thing.Percentage + '</td><td style="position: absolute; padding:0px; left:0px; width:100%;">' + '<div id="thingPlacer' + thing.Id + '"/>' + '</td></tr>')
    t.attr("class", "table table-hover")

    $("#thingsModal").on('show.bs.modal', function () {

        d3.select("#thingPlacer" + thing.Id).selectAll('svg').remove();

        var svg = d3.select("#thingPlacer" + thing.Id).append('svg')
            .attr('width', "100%")
            .attr('height', "100%")
            .append('rect')
            .attr("width", 0)
            .attr('fill', "rgba(200,0,0,0.15)")
            .transition().duration(1000).ease("linear")
            .attr('width', thing.Percentage + "%")
            .attr('height', "100%");
    });

});

这种方式的问题是d3制作的SVG将其高度设置为默认的150px(因为高度设置为100%)。这会从行中流出并流入其下方的三个中。我需要找到一种方法来使矩形与行的高度相同,或者使表格单元格的高度为行的高度并关闭溢出,或者可能使两行重叠并且行重叠。有没有办法让包含单元格的 div 与前两个 td 的高度匹配?或者我应该有另一种方法来解决这个问题吗?

我想尝试坚持使用 d3,因为他们的其他图表和图形可能会在某些时候取代普通的矩形。

编辑

通过添加以下内容,我能够让单元格使用正确的高度:

    var rowInfo;
    rowInfo = $("tr");

然后将height属性改为:

.attr('height', rowInfo.height())

但是,当切换到移动设备或更改屏幕尺寸时,这不会更新尺寸。

【问题讨论】:

    标签: javascript html css d3.js


    【解决方案1】:

    看看以下内容:

    How to make <div> fill <td> height

    如果您选择“hack”路线,请尝试将包含 tr 的最小高度设置为 1px 以使 css 可以使用。否则,您可以在渲染时根据父 tr 的高度计算高度。

    [编辑]

    可以通过附加到窗口调整大小方法来解释计算高度时的大小变化。对于这种情况,我的标准 MO 是将代码中的 resize 方法重构为可以从该方法调用的方法,然后从 $(window).resize 调用它:

    $(window).resize(function(e) {
        resizeSVG();
        });
    

    resizeSVG(); 将是您重构的方法:选择 svg,获取新的行高,然后像在当前绘制代码中一样设置高度 attr。如果需要,我会整理一个小代码示例。

    如果缩放成为问题(容器的宽度和高度可能不会调整渲染 svg 的大小),您可能希望在 svg 中包含 viewBox 属性,以控制图像在增长时的大小比例。您可以使用 .attr() 将 viewBox 属性添加到您绘制的 svg 中。

    Scaling SVG using CSS

    Applying SVG scaling with d3

    【讨论】:

    • 谢谢,我得到了正确设置的初始高度,但现在它不会在尺寸改变时更新。
    • 谢谢。我最终将大小更改应用于 div。
    猜你喜欢
    • 1970-01-01
    • 2023-03-25
    • 2020-08-30
    • 2018-04-29
    • 2013-04-29
    • 1970-01-01
    • 1970-01-01
    • 2014-12-11
    相关资源
    最近更新 更多