简单(新手)手风琴效果与标题和段落

时间:2012-10-01 02:11:38

标签: javascript html css accordion nodes

我需要知道在单击h2标题时如何创建简单的手风琴效果(只有id为“accordion”的div下的h2标签)。标题下的段落应显示隐藏或隐藏,如果它们在点击标题时显示。分配的说明在HTML代码中。我约90%,但我需要帮助看看我做错了什么。这是一个完整的新手脚本,所以我不能使用任何复杂的东西(没有innerHTML)。我需要能够到达h2标题的parentNode(具有div标签)并使用parentNode来获取h2标题下的段落子节点。所以我将在下面粘贴我的HTML,CSS和JavaScript。还有一个最后的注释,我无法改变CSS或HTML,手风琴必须基于JavaScript工作。 JavaScript必须有2个函数,只有2个函数。好的,这是代码:

HTML

        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org  /TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
        <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Best Practices - Jason McCoy</title>
        <link href="css.css" type="text/css" rel="stylesheet" />
        <script src="test.js" type="text/javascript"></script>
        </head>
        <body>
        <h1>Accordion - Jason McCoy</h1>
        <hr />
        <h2>Instructions</h2>
        <p>Create a simple accordion while implementing best practices.</p>
        <ol>
          <li>Change the part of the page heading to your name.</li>
          <li>Add your name to the &lt;title&gt; also.</li>
          <li>Create and link to an external CSS.
          <ul>
            <li>Create a class with a single declaration: <em>display:none;</em> Name the class <strong>.hideContent</strong>.  No class attribute should be added to the HTML.</li>
            <li>Create a second class with a single declaration: <em>display:block;</em> Name the class <strong>.showContent</strong>.</li>
            <li>Create two more CSS rules. One should remove the bottom margin from all H2s. The other should remove the top margin from all paragraphs.</li>
          </ul>
          </li>
          <li>Create and link to a JavaScript file.
          <ul>
          <li>Create exactly two functions. One called <strong>preparePage()</strong> that automatically applies the .hideContent style to all paragraphs within the accordion div and then makes the desired H2s call the second function when clicked. The second function,<strong>accordion()</strong>, performs the class switching.</li>
          <li>Make preparePage() run when the page loads.</li>
          <li>When an H2 inside the "accordion" div is clicked, the associated paragraph should change class so that it appears. If the paragraph is already visible, then it should disappear when its H2 is clicked.</li>
          <li>No inline JavaScript should appear in the HTML. Only a SCRIPT tag should be present in the HTML. No other JavaScript should be in the HTML anywhere.</li>
          <li>Study the HTML first so you know the structure! Similar to backing up out of folders (like you did in NOS-110 using subdirectory markers) you will have to &quot;back up&quot; out of the H2 to get its parentNode. Then you can use that parentNode to descend back down to the child paragraph.</li>
          </ul>
          </li>
        </ol>
        <p>The only changes to this HTML file should be the addition of a &lt;script&gt; tag to link to your JS file, the addition of a &lt;link&gt; tag to link to your CSS, and the addition of your name to both the title and page heading.</p>
        <div id="accordion">
        <div>
        <h2>What is Lorem Ipsum?</h2>
        <p><strong>Lorem Ipsum</strong> is simply dummy text of the printing and   typesetting industry..</p>
        </div>
        <div>
        <h2>Where does it come from?</h2>
        <p>Contrary to popular belief, Lorem Ipsum is not simply random text..</p>
        </div>
        <div>
        <h2>Why do we use it?</h2>
        <p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.</p>
        </div>
        <div>
        <h2>Where can I get some?</h2>
        <p>There are many variations of passages of Lorem Ipsum available</p>
        </div>
        </div>
        </body>
        </html>

CSS

/* create a class that hides the text */
.hidecontent {
display: none;
}

/* create a class that shows the text */
.showcontent {
display: block;
}

/* h2 rules */
h2 {
margin-bottom: 0;
}

/* paragraph rules */
p {
margin-top: 0;
}

的JavaScript

/* once the page finishes loading, run the preparePage function */
window.onload = function preparePage() {

/* Step 1: get the necessary elements needed from the accordion div section of the HTML */
    var accodion = document.getElementById('accordion');                    
var accordionHeadings = accordion.getElementsByTagName('h2');               
var accordionParagraphs = accordion.getElementsByTagName('p');                      

/* Step 2: use a for loop to set the class of the accordionParagraphs to 'hidecontent' */
for (var i = 0; i < accordionParagraphs.length; i++) {                  
    accordionParagraphs[i].className = 'hidecontent';               
}

/* Step 3: use a for loop to get to the headings
 * when a heading is clicked,
 * run the accordion function
 */
    for(var i = 0; i < accordionHeadings.length; i++) {
        accordionHeadings[i].onclick = function accordion() {
            if(accordionParagraphs.className == 'hidecontent') {
                accordionParagraphs.className = 'showcontent';
            } else {
                accordionParagraphs.className = 'hidecontent';
            }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

我认为问题在于,在第3步中,您尝试设置className accordionParagraphs,这实际上是一个数组而不是一个元素。

尝试用以下内容替换它:

accordionHeadings[i].onclick = function accordion() {

    // 'this' refers to the element that was clicked
    // 'nextElementSibling' gets the element directly after it
    var accParagraph = this.nextElementSibling;

    // now you have the right element, you can change its class
    if (accParagraph.className == 'hidecontent') {
        accParagraph.className = 'showcontent';
    } else {
        accParagraph.className = 'hidecontent';
    }
}

编辑:

你也可以这样做:

// 'this' refers to the element that was clicked (heading)
// 'parentNode' gets its parent
// 'getElementsByTagName('p')[0]' selects the first <p> element
var accParagraph = this.parentNode.getElementsByTagName('p')[0]; 

答案 1 :(得分:0)

写得很好的问题,先关闭。 使用两个功能呃?有几种不同的方法可以做到这一点。 你已经分配了onclicks,所以你的状态很好。但是你要为 accordeonParagraphs 数组赋一个类名,而不是元素。小心点。使用accordionParagraphs [i] .className ...

基本上,您需要先找到被点击标题的索引。这很容易,因为一个onclick事件向window对象注册 - 使用window.event.target获取目标对象(可能因浏览器而异,所以如果你的任务取决于它,请查看如何彻底完成 - 这适用于铬和FF肯定)。 使用它,您可以实际引用刚刚单击的对象。由于您已经有了标题列表,因此请查看它们,看看哪一个是您点击的标题:

for(var i = 0; i < accordeonHeadings.length; i++){
    if(window.event.target == accordeonHeadings[i]){

    }
}

现在在if语句中,您只需使用i的索引来访问相应的段落并进行更改。

for(var i = 0; i < accordeonHeadings.length; i++){
    if(window.event.target == accordeonHeadings[i]){
        if(accordionParagraphs[i].className == 'hidecontent') {
            accordionParagraphs[i].className = 'showcontent';
        } else {
            accordionParagraphs[i].className = 'hidecontent';
        }
    }
}

应该这样做。我没有测试这段代码,它可能包含打破它的拼写错误,所以请自己测试一下。

祝你好运兄弟。