正在获取路径的属性

Getting attribute of a path

本文关键字:属性 路径 获取      更新时间:2023-09-26

我正在尝试访问在Javascript中创建的路径的d属性。打印路径元素的结果是:

path class=​"coastline"  
 d="M641.2565741281438,207.45837080935186L640.7046722156485,207.0278378856494L640.6985715873882,207.1279196729914L640.8663103175278,207.53837609537672L640.8542041922302,207.73856415298116L641.04637606029"

路径较长。我可以使用class上的getAttribute方法访问类属性。但是,当我尝试访问d属性时,它会给我null。我还有别的事情要做吗?

编辑:这是我目前试图访问d属性的方式(我特别想要海岸线):

    var path = d3.geo.path().projection(globe.projection).pointRadius(7);
    var coastline = d3.select(".coastline");
    console.log(coastline[0][0]);
    console.log(coastline[0][0].getAttribute('class'));
    console.log(coastline[0][0].getAttribute('d'));

SVGPathElementd属性"是一个包含一系列路径描述的字符串。"

您可以通过getAttribute()/setAttribute()方法获取并设置它
一旦被浏览器解释,路径对象将包含根据该字符串创建的SVGPathSegList。这个SVGPathSegList本身将包含不同的PathSegXTo对象。

您可以访问此列表,并通过获取路径对象的pathSegList属性来修改每个Path Segments,该对象是ArrayLike对象,但只能通过getAttribute方法访问原始字符串。

var p = document.createElementNS('http://www.w3.org/2000/svg', 'path');
p.setAttribute('class', 'coastline');
svg.appendChild(p);
// set the attribute
p.setAttribute('d', 'M50,25L60,105L65,65');
// move the third point on x axis after 1 second
setTimeout(function() {
  p.pathSegList[2].x += 50;
  var coastline = d3.select(".coastline");
  // get the attribute with DOM method
  snippet.log('from getAttribute : ' + coastline[0][0].getAttribute('d'));
  // get it from d3 method
  snippet.log('from d3.attr() : ' + coastline.attr('d'));
}, 1000)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<svg id="svg"></svg>

对不起!我不想清楚地表达我的意见,请直接查看以下代码

var p = document.getElementById('test');
// general attribute | property, bi-directional
console.log(p.id);// test
console.log(p.getAttribute('id'));// test
// custom attribute,  <p class='m-test' id='test' data='data'></p> and p.setAttribute('data', 'data'); one-way, only object.getAttribute() works
console.log(p.data);// undefined
console.log(p.getAttribute('data'))// data
// custom property; one-way ,only object.propery works
p.proData = 'property';
console.log(p.proData);// property
console.log(p.getAttribute('proData'));// null
<p class='m-test' id='test' data='data'>
  this is a prograph
<p/>

您可以使用setAttribute方法设置"d"attribute,只有通过getAttribute()方法才能获得"d"属性的值。