识别边栏何时处于活动状态 [英] Recognizing when sidebar is active or not

查看:72
本文介绍了识别边栏何时处于活动状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用JavaScript识别边栏何时被归类为活动".我正在使用bootstraps的侧边栏切换按钮,当单击该按钮时,会为侧边栏分配一个活动"类.

I want to use javaScript to recognize when a sidebar is classed "active" or not. I'm using bootstraps' sidebar toggle button, which when clicked, assigns a class of "active" to the sidebar.

<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按钮时才分配活动类,而在再次单击按钮时将除去活动类.上面的代码不起作用.即使侧边栏明确分类为活动"并且可见,它也仅记录未活动".我希望它动态读取侧栏的状态(分类为活动或不活动).

To be clear, the active class is only assigned when the sidebarCollapse button is clicked, and the active class is removed when the button is clicked again. The above code doesn't work. It only logs 'not active', even when the sidebar is clearly classed 'active' and is visible. I want it to dynamically read the status of the sidebar (either classed active, or not active).

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

以下是HTML的图片,其中显示了侧边栏的两种状态(有效/无效):

Here's pictures of the HTML, showing the two states of the sidebar (active/not active):

推荐答案

您的代码应该可以工作.您的代码始终显示为不活动"的原因有两个

You code should work. There are 2 reasons why your code is always showing 'not active'

  1. 您的代码在页面加载时执行
  2. 您要在打开侧边栏并且稍后不更新dom对象之前获取侧边栏div.

将代码移至某个函数,并在需要检查时调用该函数.

Move your code to a function and call that function when ever you need to check.

下面的示例代码.

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>

这篇关于识别边栏何时处于活动状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆