Добавление активного класса в текущий элемент - PullRequest
0 голосов
/ 30 января 2019

Я хочу добавить класс активного элемента к моей текущей панели навигации, но в настоящее время не могу.

Я пробовал метод w3schools, но, возможно, я неправильно его реализовал.

КОД:

// Get the container element
var btnContainer = document.getElementsByClassName("tab");

// Get all buttons with class="btn" inside the container
var btns = btnContainer.getElementsByClassName("link");

// Loop through the buttons and add the active class to the current/clicked button
for (var i = 0; i < btns.length; i++) {
  btns[i].addEventListener("click", function() {
    var current = document.getElementsByClassName("active");
    current[0].className = current[0].className.replace(" active", "");
    this.className += " active";
  });
}
#navbar {
  position: absolute;
  text-align: right;
  top: 3.5em;
  right: 3.5em;
  z-index: 2;
}

.tab {
  background-color: white;
  opacity: 0.3;
  height: 3.5em;
  width: 0.2em;
  margin-bottom: 1em;
}

.tab:hover{
  opacity:1;
  transition:0.7s ease;
}

.link:hover > .text {
  opacity:1;
  transition:0.7s ease;
}

.active, .tab:hover {
  opacity:1;
  transition:0.7s ease;
}

.active, .text:hover > .text {
  opacity:1;
  transition:0.7s ease;
}
<div id="navbar">

	<div class="tab">

		<a class="link active" href="#home">
			<div class="text">Home</div>
		</a></div>

	<div class="tab">

		<a class="link" href="#work">
			<div class="text">Work</div>
	</a></div>
	
	<div class="tab">
		
		<a class="link" href="#about">
			<div class="text">About</div>
	</a></div>
</div>

Панель навигации в данный момент работает, но активного элемента нет.Мне бы хотелось, чтобы вкладка была непрозрачной: 1, когда активна.

Ответы [ 3 ]

0 голосов
/ 30 января 2019

В Javascript вы можете использовать .querySelectorAll () :

document.querySelectorAll('.tab .link').forEach(function(ele, idx) {
    ele.addEventListener("click", function(e) {
        e.preventDefault();
        document.querySelectorAll('.tab.active').forEach(ele => ele.classList.remove('active'));
        ele.parentNode.classList.toggle('active');
    });
});
#navbar {
  position: absolute;
  text-align: right;
  top: 3.5em;
  right: 3.5em;
  z-index: 2;
}

.tab {
  background-color: white;
  opacity: 0.3;
  height: 3.5em;
  width: 0.2em;
  margin-bottom: 1em;
}

.tab:hover{
  opacity:1;
  transition:0.7s ease;
}

.link:hover > .text {
  opacity:1;
  transition:0.7s ease;
}

.active, .tab:hover {
  opacity:1;
  transition:0.7s ease;
}

.active, .text:hover > .text {
  opacity:1;
  transition:0.7s ease;
}
<div id="navbar">
    <div class="tab">
        <a class="link active" href="#home">
            <div class="text">Home</div>
        </a></div>
    <div class="tab">
        <a class="link" href="#work">
            <div class="text">Work</div>
        </a></div>
    <div class="tab">
        <a class="link" href="#about">
            <div class="text">About</div>
        </a></div>
</div>
0 голосов
/ 30 января 2019

См. Быстрое решение jQuery ниже, используя следующие методы:

  • .on ()
  • .closest ()
  • .addClass () и
  • .removeClass ()

$(function() {
    var links = $('.tab > .link');
    links.on('click', function() {
        links.removeClass('active').closest('.tab').removeClass('active');
        $(this).addClass('active').closest('.tab').addClass('active');
    })
    .first().click();
});
#navbar {
  position: absolute;
  text-align: right;
  top: 3.5em;
  right: 3.5em;
  z-index: 2;
}

.tab {
  background-color: white;
  opacity: 0.3;
  height: 3.5em;
  width: 0.2em;
  margin-bottom: 1em;
}

.tab:hover{
  opacity:1;
  transition:0.7s ease;
}

.link:hover > .text {
  opacity:1;
  transition:0.7s ease;
}

.active, .tab:hover {
  opacity:1;
  transition:0.7s ease;
}

.active, .text:hover > .text {
  opacity:1;
  transition:0.7s ease;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="navbar">

	<div class="tab">

		<a class="link active" href="#home">
			<div class="text">Home</div>
		</a></div>

	<div class="tab">

		<a class="link" href="#work">
			<div class="text">Work</div>
	</a></div>
	
	<div class="tab">
		
		<a class="link" href="#about">
			<div class="text">About</div>
	</a></div>
</div>
0 голосов
/ 30 января 2019

Во-первых, вам нужно добавить класс в родительский div, а не в ссылку, поскольку для родительского элемента непрозрачность установлена ​​на 0,3.Теперь я сделал это в jQuery, так как этого гораздо проще достичь.Надеюсь, это не проблема.

$('.link').on('click', function() {
  $('.link').parent().removeClass('active');
  $(this).parent().addClass('active');
});
#navbar {
  position: absolute;
  text-align: right;
  top: 3.5em;
  right: 3.5em;
  z-index: 2;
}

.tab {
  background-color: white;
  opacity: 0.3;
  height: 3.5em;
  width: 0.2em;
  margin-bottom: 1em;
}

.tab:hover{
  opacity:1;
  transition:0.7s ease;
}

.link:hover > .text {
  opacity:1;
  transition:0.7s ease;
}

.active, .tab:hover {
  opacity:1;
  transition:0.7s ease;
}

.active, .text:hover > .text {
  opacity:1;
  transition:0.7s ease;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="navbar">

	<div class="tab active">

		<a class="link" href="#home">
			<div class="text">Home</div>
		</a></div>

	<div class="tab">

		<a class="link" href="#work">
			<div class="text">Work</div>
	</a></div>
	
	<div class="tab">
		
		<a class="link" href="#about">
			<div class="text">About</div>
	</a></div>
</div>
...