点击链接切换div显示状态

时间:2017-06-01 14:40:31

标签: javascript

我试图在点击各自的链接时显示每个div,但我一直收到错误

  

无法阅读属性' style'为null

虽然我的一点有用,但我不确定我是否选择了正确的语法event.target.style.display = 'none'

如何循环点击并使每个div出现而其他div在打开时消失?

JSFiddle

const tab = document.querySelector('body');
const tab1 = document.querySelector('#home')
tab.addEventListener('click', function(event){
    event.target.style.backgroundColor = 'grey';
    tab1.style.display == 'none'
})

2 个答案:

答案 0 :(得分:1)

我就是这样做的:

  1. 修复您的ID - 它们应该是唯一的,因此请从链接中删除它们
  2. 在链接中添加课程
  3. 向您的内容div添加课程
  4. 正确使用您的链接 - 让它们定位到相应的div
  5. 将内容div包装在包装div中,以便您可以使用我添加的css(参见代码)
  6. 更新js(代码注释中的注释)
  7. 
    
    var links = document.getElementsByClassName('link'),         // add a class to the links and get them all
      contentDivs = document.getElementsByClassName('content');  // same with the content blocks
    
    for (i = 0; i < links.length; i++) {                        // loop through the links to add the event listeners
      var link = links[i];
    
      // add event listener
      link.addEventListener('click', function(event) {
    
        // reset color and hide content:
        for (a = 0; a < links.length; a++) {
          // number of links should match number of content
          links[a].style.backgroundColor = 'magenta';
          contentDivs[a].style.display = 'none';
        }
    
        // set colour of clicked
        event.target.style.backgroundColor = 'grey';
    
        // show clicked content
        document.getElementById(event.target.getAttribute("href").substring(1)).style.display = 'block';
      })
    }
    &#13;
    ul {
      wudth: 100%;
      clear: both
    }
    
    li {
      padding: 10px;
      color: white;
      list-style: none;
    }
    
    li a {
      background: magenta;
      color: white;
      padding: 10px;
    }
    
    /* add this so only home is showing when page loads */
    .content:not(:first-child) {
      display: none;
    }
    &#13;
    <ul>
      <li><a href="#home" class="link">Home</a></li>
      <li><a href="#contact" class="link">Contact</a></li>
      <li><a href="#articles" class="link">Articles</a></li>
      <li><a href="#connect" class="link">Connect</a></li>
    </ul>
    
    <div>
      <div id="home" class="content">
        home
        <br> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque erat velit, placerat sit amet nisl sed, aliquet bibendum nunc. Donec varius dui sed velit volutpat, et rutrum turpis fini
      </div>
      <br>
      <div id="contact" class="content">
        contact
        <br> . Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vestibulum aliquam iaculis turpis et efficitur. Integer sollicitudin tincidunt imperdiet. Nam pharetra orci ac viverra dapibus. Ut feugiat nisi sit amet
        hendrerit scelerisque. Nulla scelerisque mauris metus, eu facilisis lectus euismod vel. Pellentesque magna mi, scelerisque vel rutrum quis, volutpat et diam.
      </div>
      <div id="articles" class="content">
        articles
        <br> . Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vestibulum aliquam iaculis turpis et efficitur. Integer sollicitudin tincidunt imperdiet. Nam pharetra orci ac viverra dapibus. Ut feugiat nisi sit amet
        hendrerit scelerisque. Nulla scelerisque mauris metus, eu facilisis lectus euismod vel. Pellentesque magna mi, scelerisque vel rutrum quis, volutpat et diam.
      </div>
      <div id="connect" class="content">
        connect
        <br> . Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vestibulum aliquam iaculis turpis et efficitur. Integer sollicitudin tincidunt imperdiet. Nam pharetra orci ac viverra dapibus. Ut feugiat nisi sit amet
        hendrerit scelerisque. Nulla scelerisque mauris metus, eu facilisis lectus euismod vel. Pellentesque magna mi, scelerisque vel rutrum quis, volutpat et diam.
      </div>
    </div>
    &#13;
    &#13;
    &#13;

答案 1 :(得分:0)

所以,我的方法是将一个事件绑定到你的所有链接,然后隐藏所有内容部分,然后显示你想要显示的部分(它们也可以默认隐藏在css中) )。所有内容部分的通用类可能对您有所帮助。我使用数据属性与可点击链接配对,因为ID每页需要唯一。

我玩了一下来演示,但还有更多的事要做,管理锚点的颜色以及所有这些。

&#13;
&#13;
const tab = document.querySelector('body');
//get all clickables
const home = document.querySelector('#home');
const contact = document.querySelector('#contact');
const articles = document.querySelector('#articles');
const connect = document.querySelector('#connect');
// loop through all clickables and bind events
[home, contact, articles, connect].forEach(function(tab){
   tab.addEventListener('click', function(event){
   			var selection = event.currentTarget.id;
        //get our content sections
        var collapse = document.querySelectorAll('.collapsible');
        for(var i = 0; i < collapse.length; i++){
                //loop through them all and hide
        		collapse[i].style.display = 'none';
        }
        
  			event.target.style.backgroundColor = 'grey';
            //show the one we want
   			document.querySelector(".collapsible[data-pair='"+selection+"']").style.display = 'block';
   })
});
&#13;
ul{
  wudth:100%;
  clear:both
}
li{
  padding:10px;
  color:white;
  list-style:none;
}
li a{
  background:magenta;
  color:white;
  padding:10px;
}
&#13;
<ul>
  <li><a href="#" id="home">Home</a></li>
  <li><a href="#" id="contact">Contact</a></li>
  <li><a href="#" id="articles">Articles</a></li>
  <li><a href="#" id="connect">Connect</a></li>
</ul>

<div id="home_content" class='collapsible' data-pair="home">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque erat velit, placerat sit amet nisl sed, aliquet bibendum nunc. Donec varius dui sed velit volutpat, et rutrum turpis fini
</div>
<br>
<div id="contact_content" class='collapsible' data-pair="contact">
. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vestibulum aliquam iaculis turpis et efficitur. Integer sollicitudin tincidunt imperdiet. Nam pharetra orci ac viverra dapibus. Ut feugiat nisi sit amet hendrerit scelerisque. Nulla scelerisque mauris metus, eu facilisis lectus euismod vel. Pellentesque magna mi, scelerisque vel rutrum quis, volutpat et diam.
</div>
<div id="articles_content" class='collapsible' data-pair="articles">
. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vestibulum aliquam iaculis turpis et efficitur. Integer sollicitudin tincidunt imperdiet. Nam pharetra orci ac viverra dapibus. Ut feugiat nisi sit amet hendrerit scelerisque. Nulla scelerisque mauris metus, eu facilisis lectus euismod vel. Pellentesque magna mi, scelerisque vel rutrum quis, volutpat et diam.
</div>
<div id="connect_content" class='collapsible' data-pair="connect">
. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vestibulum aliquam iaculis turpis et efficitur. Integer sollicitudin tincidunt imperdiet. Nam pharetra orci ac viverra dapibus. Ut feugiat nisi sit amet hendrerit scelerisque. Nulla scelerisque mauris metus, eu facilisis lectus euismod vel. Pellentesque magna mi, scelerisque vel rutrum quis, volutpat et diam.
</div>
&#13;
&#13;
&#13;

希望这对您有所帮助。

P.S。正如评论中所指出的那样,你也不希望在作业中使用双等号。