使用SVG和d3.js创建滚动条 [英] Creating scrollbars with SVG and d3.js

查看:2269
本文介绍了使用SVG和d3.js创建滚动条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我使用d3来创建几个盒子,它们只是带有文本的SVG矩形:

Right now I've used d3 to create several "boxes" that are merely SVG rectangles with text:

var canvas = d3.select("body").append("svg")
    .attr("width", 800)
    .attr("height", 500);


//specifies drawing area for each box
var boxes = canvas.selectAll("rect")
    .data(classData)
    .enter();

boxes.append("rect")
        .attr("width", boxWidth)
        .attr("height", boxHeight)
        .attr("fill", boxColor)
        .attr("x", function (d, i) { return i * 2 * boxWidth });


text.append("text")
        .attr("fill", textColor)
        .attr("x", function (d, i) 
              { return i * 2 * boxWidth + 5 })
        .attr("y", 20)
        .style("width", "20px")
        .style("overflow-x", "scroll")
        .text(function(d) {return d.name});

现在我想做的是,当文本在框的边界之外时,向每个框添加滚动条。我看到一些例子创建了一个 div 并使用CSS处理溢出。

Now what I'd like to do is add scrollbars to each box when the text is outside the bounds of the box. I've seen a couple examples that created a div and used CSS to handle the overflow. However, I will have multiple (variable) boxes and I'm not sure how to go about this.

有没有建议?

- UPDATE -

-- UPDATE --

我可以通过将svg元素附加到一个控制滚动CSS样式的div来显示滚动条。

I was able to get scrollbars to appear by appending svg elements to a div that controls scrolling with CSS styles.

.container {
    height: 225px;
    width: 175px;
    border:2px solid #000;
    overflow-y: scroll;
    overflow-x: hidden;
}

svg {
    display: block;
    width: 200%;
    height: 200%;
}

但是,滚动似乎只受宽度和高度百分比的影响svg元素而不是在div中绘制的rect元素。换句话说,如果矩形太大,你仍然不能滚动查看所有的,除非你增加了svg元素的宽度和高度。

However, the scrolling seems to be affected only by the width and height percentages of the svg element rather than the rect element that is drawn in the div. In other words, if the rectangle is too large, you still can not scroll to see all of it, unless you increase the width and height of the svg element.

有一种方法,我可以有基于它内部绘制的div滚动?或者,我应该尝试以某种方式计算和更改svg元素的宽度和高度属性?

Is there a way I can have the div scroll based on what is drawn inside of it? Or should I try to somehow calculate and change the width and height attributes of the svg element?

查看此处的代码

推荐答案

尝试添加viewBox svg属性:

Try to add the viewBox svg property:

var rectangle = container.append("svg")
    .attr("viewBox", "0,0,150,420")
    .append("rect")
    .attr("width", 150)
    .attr("height", 420)
    .attr("fill", "steelblue")
    .attr("x", 0)
    .attr("y", 0);

jsfiddle

这篇关于使用SVG和d3.js创建滚动条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆