JavaScript onClick addClass

后端 未结 3 1781
逝去的感伤
逝去的感伤 2020-12-16 16:13

I am kind of confused why my code doesn\'t work correctly, I hope You will tell me what I\'ve done wrong. I want to highlight navigation tab while clicked.

HTML:

相关标签:
3条回答
  • 2020-12-16 17:01

    var list = document.querySelector('ul');
    list.addEventListener('click', function(ev) {
      if (ev.target.tagName === 'LI') {
        ev.target.classList.toggle('checked');
      }
    }, false);

    0 讨论(0)
  • 2020-12-16 17:02

    This code will highlight the navigation tab without needing to include onclick in the HTML, though it doesn't remove the background color if another tab is clicked.

        document.onclick = function(event) {
             var target = event.target || event.srcElement;
             target.style.background = '#cf5c3f';
            };
    

    https://codepen.io/mdmcginn/pen/BwrNaj/

    0 讨论(0)
  • 2020-12-16 17:03

    You can simplify your JavaScript to:

    Fiddle

    function dodajAktywne(elem) {
        // get all 'a' elements
        var a = document.getElementsByTagName('a');
        // loop through all 'a' elements
        for (i = 0; i < a.length; i++) {
            // Remove the class 'active' if it exists
            a[i].classList.remove('active')
        }
        // add 'active' classs to the element that was clicked
        elem.classList.add('active');
    }
    

    If you pass the parameter this in your HTML to:

    <header class="mainheader">
        <!-- Obrazek tutaj-->
        <nav>
            <ul>
                <li><a id="a-home" onclick="dodajAktywne(this)" href="#">Home</a>
                </li>
                <li><a id="a-omnie" onclick="dodajAktywne(this)" href="#">O mnie</a>
                </li>
                <li><a id="a-kurs" onclick="dodajAktywne(this)" href="#">Kurs</a>
                </li>
                <li><a id="a-kontakt" onclick="dodajAktywne(this)" href="#">Kontakt</a>
                </li>
            </ul>
        </nav>
    </header>
    

    Note: I've changed href attribute to #, you will have to change it back to your .html pages


    Alternatively, you can do this without JavaScript, using CSS's :focus:

    Fiddle

    a:focus {
        color: blue;
        background-color: #cf5c3f;
    }
    
    0 讨论(0)
提交回复
热议问题