使用classList隐藏和显示元素的问题

时间:2016-12-21 18:14:57

标签: javascript html css

我需要实现一个功能,当点击另一个div时div会显示,如果再次点击div则应该隐藏。

以下是代码的一小部分:https://jsfiddle.net/6dgL6zqb/1/

var portfolio = document.getElementById('portfolio');
EventUtil.addHandler(portfolio, 'click', function(event) {
event = EventUtil.getEvent(event);
var target = EventUtil.getTarget(event);

switch(target.id) {
    case 'kk':
        console.log('kk clicked');
        var idName = target.id + 'Details',
        doc = document,
        currentProject = doc.getElementById(idName),
        otherProjects = doc.getElementsByClassName('projectDetails');
        console.log(currentProject);
        for (var i = otherProjects.length - 1; i >= 0; i--) {
            var projectClassList = otherProjects.item(i).classList;
            if (projectClassList.contains('showMe')) {
                projectClassList.remove('showMe');
                projectClassList.add('hideMe');
            }
        };
        var currentProjectClassList = currentProject.classList;
        console.log(currentProjectClassList);
        if (!currentProjectClassList.contains('showMe')) {
            currentProjectClassList.remove('hideMe');
            currentProjectClassList.add('showMe');
        } else {
            currentProjectClassList.remove('showMe');
            currentProjectClassList.add('hideMe');
        }
        break;
    }
});

我正在使用EventUtil处理程序来处理事件,以及事件委派。

因此,当我点击ID为'kk'的第1节时,会显示另一个id为'kkDetails'的div。但是,当我点击id为'kk'的div时,我希望id为'kkDetails'的div消失。我怎样才能实现这一目标?

据我所知,currentProjectClassList对象没有像我期望的那样更新。虽然,我不明白为什么。

PS:我是编程的新手,所以请忍受任何无知。

2 个答案:

答案 0 :(得分:1)

您遇到的问题是此部分:

  otherProjects = doc.getElementsByClassName('projectDetails');
  for (var i = otherProjects.length - 1; i >= 0; i--) {
            var projectClassList = otherProjects.item(i).classList;
            if (projectClassList.contains('showMe')) {
                projectClassList.remove('showMe');
                projectClassList.add('hideMe');
            }
        };

您实际上是隐藏了您的元素,然后再次显示它,作为示例,将此部分修改为:

      otherProjects = doc.getElementsByClassName('projectDetails');
      for (var i = otherProjects.length - 1; i >= 0; i--) {
                if(otherProjects.item(i).id !== idName){
                    var projectClassList = otherProjects.item(i).classList;
                    if (projectClassList.contains('showMe')) {
                        projectClassList.remove('showMe');
                        projectClassList.add('hideMe');
                    } 
                }
            };

在本节中,您将交换所选div的可见状态:

    if (!currentProjectClassList.contains('showMe')) {
        currentProjectClassList.remove('hideMe');
        currentProjectClassList.add('showMe');
    } else {
        currentProjectClassList.remove('showMe');
        currentProjectClassList.add('hideMe');
    }

但是在上一段代码中,因为所选元素还具有类 projectDetails ,所以它的 showMe 被删除,并且 hideMe 被添加。因此,当它到达上面的代码部分时,如果(!currentProjectClassList.contains('showMe'))将始终为真。

答案 1 :(得分:1)

我会使用单个类来切换可见性。它更容易管理。另外,我会通过某种属性(而不是在javascript中使用switch语句)将click元素与toggled元素链接起来。

EventUtil.addHandler(portfolio, 'click', function(event) {
  event = EventUtil.getEvent(event);
  var target = EventUtil.getTarget(event);
  var divId = target.getAttribute('href');

  if (divId) {
    event.preventDefault();
    Array
      .from(document.querySelectorAll('.projectDetails:not(.hideMe)'))
      .forEach(function(a) {
        a.classList.add('hideMe')
      });

    document.querySelector(divId).classList.remove('hideMe')
  }
});

// Cross-browser event handler
var EventUtil = {
  addHandler: function(element, type, handler) {
    if (element.addEventListener) {
      element.addEventListener(type, handler, false);
    } else if (element.attachEvent) {
      element.attachEvent("on" + type, handler);
    } else {
      element["on" + type] = handler;
    }
  },

  getEvent: function(event) {
    return event ? event : window.event;
  },

  getTarget: function(event) {
    return event.target || event.srcElement;
  },

  preventDefault: function(event) {
    if (event.preventDefault) {
      event.preventDefault();
    } else {
      event.returnValue = false;
    }
  },

  removeHandler: function(element, type, handler) {
    if (element.removeEventListener) {
      element.removeEventListener(type, handler, false);
    } else if (element.detachEvent) {
      element.detachEvent("on" + type, handler);
    } else {
      element["on" + type] = null;
    }
  },

  stopPropagation: function(event) {
    if (event.stopPropagation) {
      event.stopPropagation();
    } else {
      event.cancelBubble = true;
    }
  }
};

var portfolio = document.getElementById('portfolio');
EventUtil.addHandler(portfolio, 'click', function(event) {
  event = EventUtil.getEvent(event);
  var target = EventUtil.getTarget(event);
  var divId = target.getAttribute('href');

  if (divId) {
    event.preventDefault();
    Array
      .from(document.querySelectorAll('.projectDetails:not(.hideMe)'))
      .forEach(function(a) {
        a.classList.add('hideMe')
      });

    document.querySelector(divId).classList.remove('hideMe')
  }
});
.projectDetails {
  display: block;
}
.projectDetails.hideMe {
  display: none;
}
<body>

  <div class="container">

    <section id="portfolio">
      <div class="row">
        <div class="col-sm-4">
          <a href="#kkDetails" id="kk">Section 1</a>
        </div>
        <div class="col-sm-4">
          <a href="#arthDetails">Section 2</a>
        </div>
        <div class="col-sm-4">
          <a href="#bobyPinzDetails">Section 3</a>
        </div>
      </div>
      <div class="row">
        <div id="kkDetails" class="hideMe projectDetails">
          <p>Text</p>
        </div>
        <div id="arthDetails" class="hideMe projectDetails">
          <p>Text 2</p>
        </div>
        <div id="bobyPinzDetails" class="hideMe projectDetails">
          <p>Text 3</p>
        </div>
      </div>
    </section>

</body>