繁体   English   中英

查找CSS隐藏的div宽度

[英]Finding width of div hidden by CSS

我有一个div工具提示,我想以D3创建的SVG圆为中心。 我的mouseover事件触发div的“隐藏”类为false。

柱塞

由于div是隐藏的,因此我无法计算宽度,因此无法以所需的方式将div居中于圆上:

var width = document.getElementById("tooltip").offsetWidth;

...

.style("left", xPosition - (width/2) + "px" )

有办法解决这个问题吗?

可能值得注意的是,我不希望div具有固定的宽度。

var w = 300, h = 500;

var svg = d3.select('body').append('svg').attr('width', w).attr('height', h)

svg.append('circle').attr('r', 20)
  .attr('cx', 200)
  .attr('cy', 300)
  .on("mouseover", function(d) {
    var xPosition = parseFloat(d3.select(this).attr("cx"));
    var yPosition = parseFloat(d3.select(this).attr("cy"));
    var width = document.getElementById("tooltip").offsetWidth;

    d3.select("#tooltip")
      .style("left", xPosition - (width/2) + "px" )
      .style("top", yPosition + "px")
      .select("#value")
      .text(d);

    d3.select("#tooltip").classed("hidden", false);
  })

  .on("mouseout", function() {
    d3.select("#tooltip").classed("hidden", true);
  })

您必须首先给div一个显示值,而不是“ none”。 然后,您得到它的宽度。 然后,您可以定位它。

如果您不希望用户看到div跳转,请为其设置样式可见性:放置时将其隐藏:

CSS:

.hidden {
    display: none;
    visibility: hidden;
}

JS:

d3.select("#tooltip").style("display", "block");
// your div is still invisible, but now has a width.
// get its width and position it now
d3.select("#tooltip").classed("hidden", false); // now it will appear

如果您再次隐藏它,也不要忘记重置display样式!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM