【问题标题】:How to detect the wordpress admin bar in javascript?如何检测 javascript 中的 wordpress 管理栏?
【发布时间】:2020-04-14 09:12:20
【问题描述】:

我使用的导航栏在向下滚动页面时隐藏,在 Wordpress 中向上滚动时显示。

典型的问题是 WP 管理栏位于导航栏的顶部。

由于我的导航栏 srcoll 隐藏代码是用 javascript 制作的,所以当管理栏存在时,我无法使用之前使用的 css 代码在导航栏顶部添加空格:

body.admin-bar #navbar-section {
  top: 32px;
}

所以我想知道如何在 javascript 中检测 WP 管理栏的存在,以便我可以使用以下代码在顶部添加空格:

    if adminbar present then
document.getElementById("navbar-section").style.top = "32px";
    else
document.getElementById("navbar-section").style.top = "0px";

非常感谢,因为我已经挣扎了很长时间...... :} !

【问题讨论】:

  • 看看 wordpress 管理栏的 z-index。它应该覆盖其余的内容

标签: javascript wordpress navbar admin detection


【解决方案1】:

管理工具栏的 ID 为“wpadminbar”。所以你的代码只需要引用这个:

const $wpadminbar = document.getElementById('wpadminbar');
const $navbar_section = document.getElementById('navbar-section');
if ($wpadminbar){
     $navbar_section.style.top = "32px";
} else {
     $navbar_section.style.top = "0px";
}

你也可以使用 Node.contains:


const $wpadminbar = document.getElementById('wpadminbar');
const $navbar_section = document.getElementById('navbar-section');
if (document.body.contains($wpadminbar)){
     $navbar_section.style.top = "32px";
} else {
     $navbar_section.style.top = "0px";
}

【讨论】:

  • 非常感谢 Tokant :D !!
【解决方案2】:

有关信息,我还找到了这个解决方案来检查给定的 html 标记是否包含给定的类:

if (document.body.classList.contains('admin-bar')) { 
      document.getElementById("navbar-section").style.top = "32px";
} else {
    document.getElementById("navbar-section").style.top = "0px";
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-05
    • 2018-01-28
    • 1970-01-01
    • 2013-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多