d3.style won't设置HTML元素的宽度

d3.style won't set width of HTML element

本文关键字:元素 HTML 设置 won style d3      更新时间:2023-09-26

这个很简单,但是很奇怪:

var dims = this.placeholder.node().getBoundingClientRect();
this.mapContainer = d3.select('body').append('div')
  .classed('map-container', true)
  .style({
    position : 'absolute',
    width : dims.width,
    height : dims.height,
    top : dims.top,
    left : dims.left
  });

dims.width, dims.height等返回非零值,但我得到的div只是普通的<div class="container" style="position:absolute;"></div>

我可以在控制台设置其他样式值(d3.select('.map-container').style({color:'red','background-color':'blue'})工作得很好),但设置宽度d3.select('.map-container').style({width:30,top:40})根本没有任何作用。

这里是一个直接的jsbin,它也不能工作:http://jsbin.com/gequrasivo/1/edit?html,js,output

这是怎么回事?

这是因为CSS样式值需要一个单位。

this.mapContainer = d3.select('body').append('div')
  .classed('map-container', true)
  .style({
    position : 'absolute',
    width : dims.width + 'px',
    height : dims.height + 'px',
    top : dims.top + 'px',
    left : dims.left + 'px'
  });

没问题。