Bootstrap CSS Active Navigation

前端 未结 13 2356

On the Bootstrap website the subnav matches up with the sections and changes background color as you or scroll to the section. I wanted to create my own menu without all the

13条回答
  •  半阙折子戏
    2020-11-27 12:42

    In order to switch the class, you need to perform some JavaScript.

    In jQuery:

    $('.menu li a').click(function(e) {
      var $this = $(this);
      if (!$this.hasClass('active')) {
        $this.addClass('active');
      }
      e.preventDefault();
    });
    

    In JavaScript:

    var menu = document.querySelector('.menu');
    var anchors = menu.getElementsByTagName('a');
    
    for (var i = 0; i < anchors.length; i += 1) {
      anchors[i].addEventListener('click', function() { clickHandler(anchors[i]) }, false);
    }
    
    function clickHandler(anchor) {
      var hasClass = anchor.getAttribute('class');
      if (hasClass !== 'active') {
        anchor.setAttribute('class', 'active');
      }
    }
    

    I hope this helps.

提交回复
热议问题