首页 > 解决方案 > 当我使用 javaScript 单击元素时,我正在向元素添加 css 规则,但该规则似乎不起作用

问题描述

这是我的CSS。我的目标是.show在您单击某个选项卡时添加规则,以便它显示必要的内容,但它不起作用。

#tab-1-content, #tab-2-content, #tab-3-content {
  display: none;
}

.show {
  display: block !important;
}

这是我的整个 Javascript 页面。如果类被正确添加,我把console.logto 查看在控制台中,show每当我点击它时,它似乎是这样,但它并没有像它应该显示的那样显示内容。

const tabItems = document.querySelectorAll('.tab-item');
const tabContentItems = document.querySelectorAll('.tab-content-item');

// select tab content item
function selectItem(e) {
  removeBorder();
  removeShow();
  //Add border to current tab
  this.classList.add('tab-border');
  //Grab content item from DOM
  const tabContentItem = document.querySelector(`#${ this.id }-content`);
  //Add show class
  tabContentItem.classList.add('show');
  console.log(tabContentItem)
}

function removeBorder() {
 tabItems.forEach(item => item.classList.remove('tab-border'));

}

function removeShow() {
 tabContentItems.forEach(item => item.classList.remove('show'));
}

// Listen for tab click
tabItems.forEach(item => item.addEventListener('click', selectItem));

My Border variables work as intended, removing the border and adding it to the element I click on. I tried to just make a Netflix Landing Page clone as a bit of a project, here is the link to that website https://netflx.github.io/ . I removed the footer and Replaced the images as my anti-virus would not let me access the site. I tried to do exactly what netflix does, by having the different sections pop up when you click on the different tab elements but it does not do that. It only works for the first tab but does not show the content for the other two tabs. Does anyone know what is going on and how I can fix it?

标签: javascriptcss

解决方案


There is a problem with your HTML Syntax.

tab-2-content and tab-3-content are in the tab-1-content.

You should fix them like this

<div class="container">
    <div id="tab-1-content" class="tab-content-item"></div>
    <div id="tab-2-content" class="tab-content-item"></div>
    <div id="tab-3-content" class="tab-content-item"></div>
</div>

推荐阅读