我无法在带有D3.js的svg中选择类

kgqe7b3p  于 4个月前  发布在  其他
关注(0)|答案(1)|浏览(59)

当我在脚本中尝试这样做时:

var key="#US"
d3.select(key).style("fill", "red");

字符串
它不工作。但在控制台它的工作。
我尝试了一些功能,如document.ready或window.onload,但它从来没有工作。
经过一些尝试,我有这个:

window.onload = function() {
    Object.keys(countries).forEach(function(key){
        d3.select(key).style("fill", "red");
    });
};

Object.keys(countries).forEach(function(key){
    d3.select(key).style("fill", "red");
    console.log("t")
});


当开发控制台处于活动状态时,它可以工作,而当不处于活动状态时,它可以工作1/4。非常奇怪的错误

hpxqektj

hpxqektj1#

在下面的示例中,我下载了一个SVG world map,并通过将空格替换为连字符来修复class属性。
现在,给出一个看起来像这样的Map:

const countries = {
  '.United-States': true
};

字符串
现在,您可以选择美国及其地区,并通过以下方式填充它们red

Object.keys(countries).forEach(function(key) {
  d3.selectAll(key).style("fill", "red");
});

工作示例

如果我有时间,我可以将所有路径类名转换为2位或3位的国家代码,以简化此操作,并使其更符合您的选择策略。

const svgUrl = 'https://gist.githubusercontent.com/rmkane/4fb74736f090d9145b53e56d7e42989e/raw/e3e6fc625094ab84b3b2381afc447cf109bc601a/world.svg';
const svgContainer = document.querySelector('#svg-container');

const countries = {
  '.United-States': true
};

const parseSvg = (svgText) =>
  new DOMParser().parseFromString(svgText, 'image/svg+xml');

(async () => {
  const response = await fetch(svgUrl);
  let svgText = await response.text();
  // Fix path class names
  svgText = svgText.replaceAll(/class="(\w+)\s(\w+)"/g, 'class="$1-$2"');
  const svg = parseSvg(svgText).firstElementChild;
  // Add the SVG
  svgContainer.append(svg);
  // Highlight US and its territories
  Object.keys(countries).forEach(function(key) {
    d3.selectAll(key).style('fill', 'red');
  });
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<div id="svg-container"></div>
<!-- See: https://gist.github.com/rmkane/4fb74736f090d9145b53e56d7e42989e#file-world-svg -->

的字符串

另一个例子

下面是一个来自MapSVG的SVG:

const svgUrl = 'https://gist.githubusercontent.com/rmkane/4fb74736f090d9145b53e56d7e42989e/raw/ce11d29d4595e9c386bac41efaa82d33b8f07aec/world-2.svg';
const svgContainer = document.querySelector('#svg-container');

const countries = {
  '#US': true
};

const parseSvg = (svgText) =>
  new DOMParser().parseFromString(svgText, 'image/svg+xml');

(async () => {
  const response = await fetch(svgUrl);
  let svgText = await response.text();
  const svg = parseSvg(svgText).firstElementChild;
  svgContainer.append(svg);
  Object.keys(countries).forEach(function(key) {
    d3.selectAll(key).style('fill', 'red');
  });
})();
#svg-container svg {
  background: lightblue;
}

#svg-container svg path {
  fill: grey;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<div id="svg-container"></div>
<!-- See: https://gist.github.com/rmkane/4fb74736f090d9145b53e56d7e42989e#file-world-2-svg -->

相关问题