javascript - UL 元素宽度不随 JS 改变

标签 javascript html css

我目前有一个 ul 作为导航栏。我希望通过更改宽度来单击按钮打开它,但它不起作用。单击按钮时没有任何反应,但是它应该改变宽度并使 ul 出现。

function openNav() {
            document.getElementByClass("nav").style.width = "250px";
        }

        function closeNav() {
            document.getElementByClass("nav").style.width = "0px";
        }
.nav {
  list-style-type: none;
  margin: 0;
  padding: 0;
  width: 0;
  background-color: #f1f1f1;
  height: 100%; /* Full height */
  position: fixed; /* Make it stick, even on scroll */
  overflow: auto; /* Enable scrolling if the sidenav has too much content */
  transition: 0.5s;
}

.nav li a {
  display: block;
  color: #000;
  padding: 8px 16px;
  text-decoration: none;
}
<button onclick="openNav()">Open Nav</button>

    <ul class="nav">
        <li><a href="{% url 'sheets:list' %}" class="">Nav Element</a></li>
    </ul>

最佳答案

没有 getElementByClass() 这样的东西,您应该改用 getElementsByClassName(),就像下面的代码示例:

function openNav() {
  document.getElementsByClassName("nav")[0].style.width = "250px";
 }

function closeNav() {
  document.getElementsByClassName("nav")[0].style.width = "0px";
}

关于javascript - UL 元素宽度不随 JS 改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58805196/

相关文章:

css - 实现具有独立行高的多列布局

javascript - 如何从 JS 中的监听器函数内访问对象

javascript - 如何在javascript中动态构建json数组

html - 如何在将鼠标悬停在不同 div 中的另一个图像上时显示图像

css - 从显示中移除图像后重新定位表单

html - 宽度 : 50% mean when the container is body? 是什么意思

javascript - 正则表达式根据文本过滤图像

javascript - 我需要一种订购对象的方法

javascript - 如何使用 jquery 停止 $(window).scroll 事件?

javascript - 如何重置最近的跨度对象的文本?