亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

導航欄不再滾動到頁面上的部分?

導航欄不再滾動到頁面上的部分?

臨摹微笑 2023-11-13 10:16:45
我向導航欄添加了一個 li,突然間,每當我單擊菜單項時,它就不再滾動。我需要使用 Javascript 讓我的導航欄滾動到我的部分。這是我用 Javascript 創建的導航欄const navMenu = document.querySelectorAll("section");const navList = document.getElementById("navbar__list");const items = ["Section 1", "Section 2", "Section 3", "Section 4"];//Build the navitems.forEach((item, i) => {  const el = document.createElement("a");  el.innerText = item;  el.classList.add("menu-items");  el.setAttribute("id", `menu-${i + 1}`);  el.href = `#section${i + 1}`;  navList.appendChild(el);  const li = document.createElement("li");  li.classList.add("menu-list");  li.appendChild(el);  // Append the list item to the list  navList.appendChild(li);});//Make Nav Active when Clicked and scrolls down to sectiondocument.addEventListener("click", function (event) {  let active = document.querySelector(".menu-list.active");  if (active) active.classList.remove("active");  if (event.target.classList.contains("menu-list")) {    event.target.classList.add("active");  }});在我只添加了 a 標簽之前,我在 addEventListener 中定位了 .menu-items 而不是 .menu-list,但是一旦我將 li 標簽添加到我的導航欄,li 的類就不起作用了。我不確定要編輯或更改什么
查看完整描述

1 回答

?
函數式編程

TA貢獻1807條經驗 獲得超9個贊

系統的想法是給菜單項一個 id 并使用 id 在這里滾動你忘了給 element 提供 id 。然后我將其放在您的點擊事件中,使用此 id 獲取該部分的 id 和 href。


items.forEach((item, i) => {

  const el = document.createElement("a");

  el.innerText = item;

  el.classList.add("menu-items");

  el.setAttribute("id", `menu-${i + 1}`);

  el.href = `#section${i + 1}`;

  navList.appendChild(el);


  const li = document.createElement("li");

  li.classList.add("menu-list");

  li.appendChild(el);

  li.setAttribute("id", `${i + 1}`);

  // Append the list item to the list

  navList.appendChild(li);

});


//Make Nav Active when Clicked and scrolls down to section

document.addEventListener("click", function (event) {

  let active = document.querySelector(".menu-list.active");

  if (active) active.classList.remove("active");

  if (event.target.classList.contains("menu-list")) {

    event.target.classList.add("active");

    console.log(event.target.id);

    window.location.href="#section"+event.target.id

  }

});



查看完整回答
反對 回復 2023-11-13
  • 1 回答
  • 0 關注
  • 156 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號