隐藏并显示时按ID获取元素:无

时间:2019-01-12 02:50:49

标签: javascript reactjs d3.js

我正在使用React,并且试图通过id获取元素。我知道我应该为此使用ref,但是我无法使其正常工作。但是,d3的工作原理是:它得到我想要的元素,但没有得到上面带有visibility: hiddendisplay:none的元素。是否可以使d3选择隐藏的元素?这是我拥有的部分代码:

<div style={{display: this.state.fullAnalysisDone && this.state.activeKey === 0 ? 'block' : 'none', 
      visibility: this.state.fullAnalysisDone && this.state.activeKey === 0 ? 'visible' : 'hidden'}}>
        {
        this.get_analysis_charts(this.chartTypes[this.state.activeKey]).map((chart_img, idx) => {
          return <img id = {'chart_' + this.state.activeKey + '_' + idx} src = {chart_img} style = {{width:"400px"}}
            onClick={() => this.clickedResultPageImg(idx)}/>
        })
      }
    </div>

当我尝试通过隐藏的div中的imgid获取d3.select(chartId).node()时,我什么也没得到。这可能是stackoverflow上未解决的同一问题:

getElementById() fails to get element when display:none

1 个答案:

答案 0 :(得分:-2)

在我的浏览器中,即使getElementByIdd3.select()均为div,它也适用于p{ display:none; visibility: hidden; }

具有隐藏的p和隐藏的img

function changePara(paraId, newColor) {
  var elem = document.getElementById(paraId);
  console.log("changePara", paraId, elem);
  if (elem) { elem.style.color = newColor; }
}

function changeColor(newColor) {
  changePara('para1', newColor);
  changePara('para2', newColor);
}

function changeParaD3(paraId, newColor) {
  var elem = d3.select(`#${paraId}`);
  console.log("changeParaD3", paraId, elem.size());
  if (elem.size()) { elem.style("color", newColor); }
}

function changeColorD3(newColor) {
  changeParaD3('para1', newColor);
  changeParaD3('para2', newColor);
}
.nosee { display:none; visibility: hidden; }
#para2 { display:none; visibility: hidden; }
<script src="https://d3js.org/d3.v5.min.js"></script>

<div class="see"><p id="para1">Some text</p></div>
<div class="nosee"><img id="para2" src="https://cdn.sstatic.net/Img/unified/sprites.svg"/></div>


<button onclick="changeColor('blue');">blue</button>
<button onclick="changeColor('red');">red</button>
<br/><br/>
<button onclick="changeColorD3('blue');">blue-d3</button>
<button onclick="changeColorD3('red');">red-d3</button>