使用 D3 设置 div 宽度

Zen*_* Qu 5 html javascript d3.js

div在我的html,

<div id="search"></div>
Run Code Online (Sandbox Code Playgroud)

我想在我的 Javascript 中将其宽度设置为窗口宽度的 15%。我正在尝试使用 D3 来做到这一点:

var width = 0.15 * window.innerWidth,
    height = 0.95 * window.innerHeight;

var searchcolumn = d3.select("#search")
                    .attr("width", width)
                    .attr("height", height);
Run Code Online (Sandbox Code Playgroud)

我可以在 DOM 中看到,我的 div 的宽度和高度已更改: 在此处输入图片说明

但是,在呈现的 html 中,div它只是10px x 10px.

在此处输入图片说明

为什么会发生这种情况?我没有任何CSS覆盖div. 我如何设置div我想要的宽度?

tha*_*Guy 5

This is an old post but for anyone else wanting to solve this, the following will work :

var width = 0.15 * window.innerWidth,
    height = 0.95 * window.innerHeight;

var searchcolumn = d3.select("#search")
                    .style("width", width + 'px')
                    .style("height", height + 'px');
Run Code Online (Sandbox Code Playgroud)

I have added is + 'px'; and also changed .attr to .style as it's the CSS you are working with here.

Working code :

var width = 0.15 * window.innerWidth,
    height = 0.95 * window.innerHeight;

var searchcolumn = d3.select("#search")
                    .style("width", width + 'px')
                    .style("height", height + 'px');
Run Code Online (Sandbox Code Playgroud)
var data = [10,12,6,8,15];

var svg = d3.select('body')
//.append('svg')
.attr('width', 500).attr('height', 500);

var width = 0.15 * window.innerWidth,
    height = 0.95 * window.innerHeight;
     
svg.selectAll('div')
  .data(data)
  .enter().append('div')
  .attr('class','divs')
  .attr('x', function(d,i) { d.clicked=false; return 100+100*i; })
  .attr('y', function(d,i) { return 0; })
  .style('width', width + 'px')
  .style('height',height +'px')
  .attr('background-color', function() { return 'red'; }) 

  .text(function(d){ return d;})
Run Code Online (Sandbox Code Playgroud)
.divs { 
  background: blue;  
  display:inline-block;
  float:left;
  margin:5px;
}
Run Code Online (Sandbox Code Playgroud)


小智 3

尝试:
d3.select("#search") .style("height", height) .style("width", width);