javascript - 如何使用 css 媒体查询隐藏以编程方式添加的 html 元素?

标签 javascript html css google-maps

在我的 View 初始化后,我使用 JavaScript 将一个按钮添加到我的 google map 区域:

let centerControlDiv: any = document.createElement('div');
centerControlDiv.className = 'collapseButton'; //trying to hide it by css
let controlUI = document.createElement('div');
centerControlDiv.appendChild(controlUI);

this.controlText = document.createElement('button');
this.controlText.innerHTML = '<i class="fa fa-angle-double-down" aria-hidden="true"></i>';
controlUI.appendChild(this.controlText);

map.controls[google.maps.ControlPosition.BOTTOM_LEFT].push(centerControlDiv);

但是,我只想在小屏幕上显示该按钮。因此我添加了以下媒体查询:

  @media (min-width: 0px) and (max-width: 992px) {
    .collapseButton {
      display: block  !important;
    }
    /* show it on small screens */
  }

  @media (min-width: 993px) {
    .collapseButton {
      display: none  !important;
    }
    /* hide it elsewhere */
  }

由于某种原因,这不起作用。如果我这样做:

document.getElementsByClassName("collapseButton")[0].style.display = 'none';

按钮隐藏成功。 我错过了什么?

更新:这是包括按钮在内的 DOM 片段: enter image description here

最佳答案

我终于找到了解决方案:

@media (min-width: 0px) and (max-width: 992px) {
  /deep/.collapseButton {
    display: block;
  }
  /* show it on small screens */
}

@media (min-width: 993px) {
  /deep/.collapseButton {
    display: none;
  }
  /* hide it elsewhere */
}

添加 /deep/ 使其工作。仍然不知道为什么我必须添加这个。任何解释表示赞赏。

关于javascript - 如何使用 css 媒体查询隐藏以编程方式添加的 html 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47849846/

相关文章:

javascript - Canvas 上下文 "bezierCurveTo"在 Chrome 16+/Safari 5+ 下存在错误

html - 将表格转换为CSS

jquery - 在我的简单响应式菜单中添加一个简单的下拉菜单

javascript - 在jquery中使用索引动画元素

html - 在 Chrome 中将插入符定位在具有大行高的 contenteditable 中

php - 如何调用多个JS和多个CSS

html - 如何在不改变父级显示样式的情况下水平对齐两个按钮

jquery - CSS Transition div 容器高度从 100% 到 200%

javascript - Componentart 对话框无法在 IE 中运行(无法获取未定义或 null 引用的属性 'clear')

javascript - 设置为带有大量 ""的变量文本