2013-03-21 28 views
0

希望我的问题是达到标准(我整个上午都在研究这个,所以我希望我是不够彻底)getElementsByClassName方法及... ByTagName,<path>和<svg>,使用的onclick =“”改变风格

我学习所有这个新的html5,所以我可以使用一些Javascript来使用SVG,<canvas>和CSS3制作交互式绘图。我试图摆脱我曾经做过的丑陋和多余的功能,并且很好地整理了我的编码。

我在为一个<button>的onclick事件创建javascript的问题,以改变包含SVG中所有路径的类的样式,使用document.getElementsByClassName。 我已经与document.getElementById一起工作,但我想一次影响多条路径,而不必浪费大量的线路将完整的数百个ID抓取到一个var或类似的东西。

这是我的代码到目前为止,第一个按钮的作品,接下来的两个是我遇到了麻烦。

<head> 
<style> 
    .pathclass { 
fill:none; 
stroke:#ffffff; 
stroke-width:4; } 
</style></head> 

<body> 

<button onclick="document.getElementById('pathId').style.stroke = '#000000';" /> 
<br /> 
<button onclick="document.getElementsByClassName('pathClass').style.stroke = '#000000';" /> 
<br /> 
<button onclick="document.getElementsByTagName('path').style.stroke = '#000000';" /> 

<svg><g><path id="pathId" class="pathclass" /></g></svg> 

接下来,我想这样做document.getElementsByClassName它返回一个节点列表设置classNames automatcally使用的东西都喜欢document.getElementsTagName('path').className = 'pathclass'

+0

document.querySelector and document.querySelectorAll – Geuis 2013-03-21 18:32:01

+0

感谢Geuis。我查看了它,但它表示它只返回匹配选择器的第一个单个元素。我正在寻找一种方法来一次选择具有相同类的所有元素。 – user2196381 2013-03-21 18:41:27

+0

@Geuis的功能类似于@ Duopixel的答案中提到的'd3.selectAll'吗? – user2196381 2013-03-21 19:15:04

回答

1

。的NodeList类似于一个数组,你必须通过它以迭代应用样式:

// collect all nodes with class='oldclass' 
var nodes = document.getElementsByClassName('oldclass'); 
// loops to get each node in our NodeList 
for (var i=0, length = nodes.length; i < length; i++) { 
    // i starts at 0 and increments with each loop (i++ increments i on each iteration) 
    // it won't stop until it reaches the number of nodes (i < length) 
    // so on the first iteration it will be nodes[0] 
    // which is your first element, the second time 
    // it will be nodes[1] which is your second, and so on 
    nodes[i].style.stroke = "black"; 
} 

var paths = document.getElementsByTagName('path'); 
for (var i=0, length = paths.length; i < length; i++) { 
    paths[i].className = "newclass"; 
} 

现在,这是非常繁琐的,而这也正是JavaScript库开始发挥作用。我会推荐D3.js,因为它对SVG非常有用。使用D3的等效代码将是:

d3.selectAll(".oldclass").style("stroke", "black"); 
d3.selectAll("path").attr("class", "newclass"); 
+0

,这看起来就像在那里的答案!现在我所要做的就是了解XD。假定所有路径都是:1)不在单独的文档中; 2)已经标记了class =“pathClass”,对吗? – user2196381 2013-03-21 18:49:38

+0

@ user2196381我评论过的代码更清晰。 – Duopixel 2013-03-21 18:59:13

+0

完美,现在我的问题是,如何使用这个相同的安装程序来预先执行'nodes [i] .className =“newclass”'部分,使用'document.getElementsByTagName('path')' – user2196381 2013-03-21 20:28:59