我想使用JavaScript来识别边栏何时被分类为“活动”。我正在使用bootstraps的侧边栏切换按钮,当单击该按钮时,会为侧边栏分配一个“活动”类。
<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'))
要清除,仅在单击sidebarCollapse按钮时才分配活动类,而在再次单击该按钮时,将移除活动类。上面的代码不起作用。即使侧边栏明确分类为“活动”并且可见,它也仅记录“未活动”。我希望它动态读取侧栏的状态(分类为活动或不活动)。
var sideBar = document.getElementById('sidebar');
console.log(sideBar.className)
if (sideBar.classList.contains('active')){
console.log('active')
}
else (console.log('not active'))
这里是HTML的图片,显示了侧边栏的两种状态(有效/无效):
[添加下面的代码以观察更改:
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。
您的代码应该可以工作。您的代码始终显示为“不活动”的原因有两个:
将代码移至函数并在需要检查时调用该函数。
下面的示例代码。
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>