带有 D3 的 SVG 元素中的滚动条

Dar*_*ius 4 svg scrollbar d3.js

当 SVG 的大小不足以显示所有元素时,尝试在 SVG 中添加滚动条,但未成功。在这种情况下,尝试显示所有 15 个矩形,但最多只能达到 SVG 画布的大小。向 css 添加“溢出”没有帮助。任何建议如何启用垂直滚动条?

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>D3 World Map</title>
    <script src="https://d3js.org/d3.v4.min.js"></script>
    <style>
        #halfpage{
            background: "white";
            overflow-y: scroll;
        }
    </style>
  </head>
  <body>
  <script type="text/javascript">

  var elements = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];

  var svgContainer = d3.select("body").append("svg")
    .attr("width", 1200)
    .attr("height", 700)
    .attr("id", "halfpage");

    svgContainer.selectAll("rects1")
                .data(elements)
                .enter()
                .append("rect")
                .attr("width", 50)
                .attr("height", 20)
                .attr("x", 475)
                .attr("y", function(d, i){
                    return 100 * i;
                })
                .style("fill", "brown");

    </script>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

Dar*_*ius 6

基本上,我只需要添加一个div在顶部元素svg元素,使div量比较小svg

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>D3 World Map</title>
    <script src="https://d3js.org/d3.v4.min.js"></script>
    <style>
        div#halfpage{
        height: 900px;
        width: 800px;
        border:2px solid #000;
        overflow-y: auto;
        }
        svg#sky {
          height: 1000px;
          width: 1100px;
          border:1px dotted #ccc;
          background-color: #ccc;
       }
    </style>
  </head>
  <body>
  <script type="text/javascript">

  var elements = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];

  var container = d3.select("body").append("div")
    .attr("id", "halfpage");

    var svgContainer = container.append('svg')
        //.attr('height', 100)
        //.attr('width', 100)
        .attr('id', 'sky');

    svgContainer.selectAll("rects1")
                .data(elements)
                .enter()
                .append("rect")
                .attr("width", 50)
                .attr("height", 20)
                .attr("x", 475)
                .attr("y", function(d, i){
                    return 100 * i;
                })
                .style("fill", "brown");

    </script>
  </body>
Run Code Online (Sandbox Code Playgroud)

答案来自这里:https : //stackoverflow.com/a/11449016/2838794