简体   繁体   English

适用于 codepen.io,但不适用于 Visual Code Studio?

[英]Works in codepen.io, but not in Visual Code Studio?

This line of code works in codepen.io, but not in visual code studio.这行代码在 codepen.io 中有效,但在 Visual Code Studio 中无效。 When I open up a html file with link to the js in chrome, an error shows up that the my var nav is null, but when I used the code in codepen.io.当我打开一个 html 文件并链接到 chrome 中的 js 时,错误显示我的 var nav 是 null,但是当我使用 codepen.ZF98ED07A4D5F50F477DE1410D905FZ 中的代码时。 The code works.该代码有效。 I am trying to get a sidebar to appear and disappear when you click当您单击时,我试图让侧边栏出现和消失

let nav = document.querySelector('nav')
function toggleNav() {
  if (nav.classList.contains('is-open')) {
    nav.classList.remove('is-open')
  } else {
    nav.classList.add('is-open')
  }
}

here is the hmtl:这是hmtl:

<button onclick="toggleNav()"> Click me for side bars </button>
<nav class="" >
    <a href="#">This is a link</a>
    <a href="#">This is a link</a>
    <a href="#">This is a link</a>
    <a href="#">This is a link</a>        
</nav>

and here is the css if you want to see what is-open is:如果你想看看什么是开放的,这里是 css:

body {overflow:hidden}
a {
    border-width: 2px 4px 2px 4px ;
    text-decoration: none;
    margin: 0px;
    margin-top: 10px;
    padding: 5px;
    display: block;
    width: auto;
    height: 30px;
    border: solid brown;
    color: brown;
    background-color: darkgrey;
    margin: 0px;
}

.is-open {
    transform: translateX(-300px);
}

Try adding it to function like this !!尝试像这样将其添加到 function !

function toggleNav() {
  let nav = document.querySelector('nav')
  if (nav.classList.contains('is-open')) {
    nav.classList.remove('is-open')
  } else {
    nav.classList.add('is-open')
  }
}

Or或者
Just add JS at the bottom of the Page.只需在页面底部添加 JS。 When your Js code will be executed it will look for the 'nav' and it won't be able to find it when your page has just started to load.当您的 Js 代码将被执行时,它会寻找“导航”,而当您的页面刚刚开始加载时,它将无法找到它。

Check this Answer for more details: https://stackoverflow.com/a/1829934/3995126检查此答案以获取更多详细信息: https://stackoverflow.com/a/1829934/3995126

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM