【问题标题】:How to add an event listener when an element is transformed?转换元素时如何添加事件侦听器?
【发布时间】:2015-05-30 00:59:33
【问题描述】:

我正在使用具有许多功能的 Bootstrap 3 开发一个响应式网站,其中之一是当网站显示在移动设备上时,会显示下拉菜单(在桌面上我有一个普通菜单,而在移动版本上它转换成折叠下拉菜单)现在我的问题是我需要一个事件监听器,当这个普通菜单转换成这个折叠下拉菜单时,它能够监听,有没有办法做到这一点?非常感谢。

HTML 代码:

<div class="container-sm visible-sm visible-xs container visible-md visible-lg">
    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
        <span class="sr-only">Left Menu</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
    </button>
    <div class="navbar-collapse collapse">
        <div id="sideNavBox" class="ms-dialogHidden ms-forceWrap ms-noList">
            <!-- A lot of code that I included in the dropdown menu -->
        </div>
    </div>
</div>

CSS:

@media (min-width: 768px) {
  .navbar-toggle {
    display: none;
  }

.navbar-toggle {
  position: relative;
  padding: 9px 10px;
  margin-top: 8px;
  margin-bottom: 8px;
  background-color: rgb(241, 241, 241);
  background-image: none;
  border: 1px solid rgb(241, 241, 241);
  border-radius: 4px;
  width: 695px;
}

那么基本上我如何添加一个事件侦听器来检测我的菜单何时转换为折叠下拉菜单?

【问题讨论】:

  • 你不能使用window.matchMedia吗?类似:'if (window.matchMedia("YourMediaRule").matches)...'

标签: jquery html css twitter-bootstrap-3


【解决方案1】:

你可以使用window.matchMedia来创建这样的事件,见minimal code example here

var mql = window.matchMedia('only screen and (min-width: 768px)'),
    handleMQL = function(mql) {
        if (mql.matches) {
            console.log('MATCH');
            // Media query does match
            // fire your on event here 

        } else {
            console.log('UNMATCH');
            // Media query does not match anymore
            // fire your off event here 
        }
    };


mql.addListener(handleMQL);
// this is optional (in case you need the state on page load)
// see info below.
handleMQL(mql);

当目标媒体查询的状态发生变化时,监听器会被触发。如果您在页面加载时需要媒体查询的状态,请创建一个处理状态更改的函数,您也可以像上面的示例一样自行调用该函数。

如果您需要旧版浏览器支持,您可以使用像 matchMedia.js 这样的 polyfill

【讨论】:

    猜你喜欢
    • 2021-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-06
    • 1970-01-01
    • 2019-02-08
    相关资源
    最近更新 更多