识别侧边栏何时处于活动状态

Recognizing when sidebar is active or not

我想使用 javaScript 来识别边栏何时 classed "active" 或不。我正在使用引导程序的侧边栏切换按钮,单击该按钮时,会将 "active" 的 class 分配给侧边栏。

<button type="button" id="sidebarCollapse" class="btn btn-info" style="font-family:'Poppins'; position:absolute; z-index:9; margin-left:7vh; margin-top:2vh;font-size: 1.5em">
                    <span class="glyphicon glyphicon-filter"></span> Filter
                </button>

CSS:

    #sidebar {
    background: #202020;
    color: #fff;
    display:inline-block;   
    }

    #sidebar.active {
    margin-left: -250px;
    } 

还有,JS:

//Check to see whether sidebar has class 'active'
var sideBar = document.getElementById('sidebar')
        console.log(sideBar.className)
        if (sideBar.className == ('active')){
                console.log('active')
            }
        else (console.log('not active'))

需要明确的是,激活的 class 仅在单击 sidebarCollapse 按钮​​时分配,再次单击该按钮时移除激活的 class。上面的代码不起作用。它只记录 'not active',即使侧边栏明显 classed 'active' 并且可见。我希望它动态读取侧边栏的状态(classed 活动或不活动)。

var sideBar = document.getElementById('sidebar');
console.log(sideBar.className)
if (sideBar.classList.contains('active')){
    console.log('active')
}
else (console.log('not active'))

这是 HTML 的图片,显示了边栏的两种状态(active/not 活动):

使用MutationObserver.

添加以下代码以观察变化:

const targetNode = document.getElementById('sidebarCollapse'); //listen to the sidebar

const config = { attributes: true }; //listen for changes in attributes

const callback = function(mutationsList, observer) {
    for(let mutation of mutationsList) {
        if (mutation.type === 'attributes') {
          if (targetNode.classList.contains('active')){
            console.log('active');
            }
        }
    }
};

const observer = new MutationObserver(callback); //construct observer

observer.observe(targetNode, config); //start observing

一支工作笔here.

您的代码应该可以工作。您的代码总是显示 'not active'

有两个原因
  1. 您的代码在页面加载时执行
  2. 您在边栏打开之前获取边栏 div,dom 对象稍后不会更新。

将您的代码移动到一个函数中,并在需要检查时调用该函数。

示例代码如下。

function isSidebarOpen() {

  var sideBar = document.getElementById('sidebar');

  //console.log(sideBar.classList)
  if (sideBar.classList.contains('active')) {
    console.log('active')
  } else(console.log('not active'))

}
<div id="sidebar" class="active">
  test
  <button onclick='isSidebarOpen()'>
Check</button>

</div>