gpt4 book ai didi

javascript - 如何使用 svg 多边形自定义属性 (data-*) 来设置这些相同多边形的样式?

转载 作者:太空宇宙 更新时间:2023-11-04 15:47:54 25 4
gpt4 key购买 nike

我对编程和编码非常陌生。我正在使用 Adob​​e Illustrator 生成的 .svg 文件通过 d3.js 制作交互式 map 。

这个 SVG 由 g 组织而成,其中多边形内部有自己的 id。我还添加了 SVG 中每个多边形的自定义数据 (data-price="number"):

<g id="price-range">
<polygon id="name" data-price="price number" points="..."/>
<polygon id="name2" data-price="price2 number" points="..."/>
// and so on
</g>

我想使用这些自定义数据属性作为数据来为每个多边形生成不同样式的输出。这是我到目前为止的代码(它不起作用):

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>D3 Test</title>
<script type="text/javascript" src="d3/d3.js"></script>
<style type="text/css">
#map-block {
width: 100%;
max-width: 1000px;
align-content: center;
margin: auto; }
</style>
</head>
<body>
<div id="map-block">
<svg id="mapa-usados-sp" width="100%"></svg>
</div>

<script>
var svg = null;
var mapa = null;

d3.xml("sp.svg", function(error, xml) {
if (error) throw error;

var domSVG = document.getElementById('mapa-usados-sp');
domSVG.appendChild(xml.documentElement.getElementById('mapa'));

svg = d3.select(domSVG);
mapa = svg.select('#mapa');

var xmlSVG = d3.select(xml.getElementsByTagName('svg')[0]);
svg.attr('viewBox', xmlSVG.attr('viewBox'));

var bg = mapa.selectAll("g#contexto");
bg.style("fill", "#e9e9e9");

var shapes = mapa.select("g#zones").selectAll("polygon");
var price = shapes.(xml.documentElement.getAttribute('data-
price'));
shapes.style("fill", function(price) {
if (price = 0) { return "#323232";}
if (price <= 1700 && price > 0 ) {return "#2169dd";}
if (price > 1700 && d <= 2500) {return "#6921dd";}
});
});
</script>
</body>
</html>

我选择不引用每个形状的 id 或类来设置其样式,因为我真的很想使用 .svg 文件中的自定义数据属性来生成视觉输出。

最终这将是一个非常有活力的作品。我将添加交互和事件监听器,因此这就是为什么我非常有兴趣了解如何从 .svg 属性中提取数据并使用它来设置包含这些属性的形状的样式。

我希望我正确地表达了我的观点。

最佳答案

获取每个多边形的“数据”属性的方法是使用 dataset :

The HTMLElement.dataset property allows access, both in reading and writing mode, to all the custom data attributes (data-*) set on the element, either in HTML or in the DOM.

在您的情况下,其中 this 是当前 DOM 元素:

this.dataset.price

请注意,这将返回一个字符串,您可能想将其强制为数字。

这是演示,使用 data-price 的值来填充多边形:

var svg = d3.select("svg");

var shapes = svg.selectAll("polygon");

shapes.each(function() {
var thisPrice = +this.dataset.price;
d3.select(this).attr("fill", thisPrice === 0 ? "#323232" :
thisPrice > 1700 ? "#6921dd" : "#2169dd")
})
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg>
<polygon id="name1" data-price="0" points="30,10 10,50 50,50" />
<polygon id="name2" data-price="1000" points="80,10 60,50 100,50" />
<polygon id="name3" data-price="2000" points="130,10 110,50 150,50" />
</svg>

PS:如果该值高于2500,则不清楚颜色是什么。

关于javascript - 如何使用 svg 多边形自定义属性 (data-*) 来设置这些相同多边形的样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43402525/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com