0

我正在尝试使用 JavaScript 动态创建路径,但该d属性不断给出Uncaught SyntaxError: Unexpected token ILLEGAL.

var location = document.createElementNS(svgns,"path");
    location.setAttributeNS("fill-rule","evenodd");
    location.setAttributeNS("fill","#ffffff");
    location.setAttributeNS("clip-rule","evenodd");
    location.setAttributeNS(null,"d","M57.295,27.757c-11.896,0-21.539,9.643-21.539,21.539S57.295,86.5,57.295,86.5
    s21.539-25.309,21.539-37.205S69.19,27.757,57.295,27.757z M57.295,60.039c-6.373,0-11.539-5.166-11.539-11.539
    s5.166-11.539,11.539-11.539S68.833,42.127,68.833,48.5S63.667,60.039,57.295,60.039z");

    locationBTn.appendChild(locationStroke0);
    locationBTn.appendChild(location);

    document.getElementsByTagName('svg')[0].appendChild(locationBTn);
4

1 回答 1

1

像这里一样指定路径数据时要小心。换行会引起麻烦。

作为一个简化的例子:

location.setAttributeNS(null,"d","M5.5,
27.2,
c11.89,
0-21.5,9.6");

不一样

location.setAttributeNS(null,"d","M5.5,27.2,c11.89,0-21.5,9.6");

你有几个选择:

A)把它放在一行上:

location.setAttributeNS(null,"d","M57.295,27.757c-11.896,0-21.539,9.64321.539,21.539S57.295,86.5,57.295,86.5s21.539-25.309,21.539-37.205S69.19,27.757,57.295,27.757z M57.295,60.039c-6.373,0-11.539-5.166-11.539-11.539s5.166-11.539,11.539-11.539S68.833,42.127,68.833,48.5S63.667,60.039,57.295,60.039z");

(可能难以阅读和使用)

B) 使用多个字符串和 + 运算符:

location.setAttributeNS(null,"d","M57.295,27.757"+
"c-11.896,0-21.539,9.64321.539,21.539S57.295,86.5,57.295,86.5s21.539-25.309,21.539-37.205S69.19,27.757,57.295,27.757z "+
"M57.295,60.039"+
"c-6.373,0-11.539-5.166-11.539-11.539s5.166-11.539,11.539-11.539S68.833,42.127,68.833,48.5S63.667,60.039,57.295,60.039z");

(也许是最常见的解决方案)

或者

C) 使用 \ 转义返回字符并得到一个多行字符串:

location.setAttributeNS(null,"d","M57.295,27.757c-11.896,0\
-21.539,9.64321.539,21.539S57.295,86.5,57.295,86.5s21.539-25.309,\
21.539-37.205S69.19,27.757,57.295,27.757z M57.295,60.039c-6.373,\
0-11.539-5.166-11.539-11.539s5.166-11.539,11.539\
-11.539S68.833,42.127,68.833,48.5S63.667,60.039,57.295,60.039z");

(一个奇怪但有效的解决方案)


有关 SVG 的“d”字符串中可以使用哪些字符的详细信息,请查看http://www.w3.org/TR/SVG/paths.html#PathDataBNF


PS - 确保locationStroke0);不是错字locationStroke);

于 2013-04-22T02:03:49.003 回答