简体   繁体   English

jQuery .toggle()和媒体查询

[英]jQuery .toggle() and Media Queries

I'm using .toggle() on a button element: 我在button元素上使用.toggle()

$("header button").click(function(event){
    $(".site-nav-wrapper").toggle();
    event.preventDefault();
});

This works great. 这非常有效。 The problem is if the button is toggled to display:none and then I change the device orientation, triggering my desktop media query, despite the fact I re-force display:block; 问题是如果button切换到display:none然后我更改设备方向,触发我的桌面媒体查询,尽管我重新强制display:block; on the desktop media query, the button remains toggled to display:none : 在桌面媒体查询上,该button仍然切换为display:none

(Sass): (萨斯):

.site-nav-wrapper{

            //Mobile First
            display:none;

            @include breakpoint($breakpoint-lg) {
                display:block;
            }
}

Is there a way to reset whatever the toggle() function is storing? 有没有办法重置toggle()函数存储的内容?

toggle uses inline styling, which overrides whatever you're doing in your stylesheet. toggle使用内联样式,它会覆盖您在样式表中执行的任何操作。

To get the desired result, you should use a special hidden class to hide the element, and use toggleClass instead. 要获得所需的结果,您应该使用特殊的hidden类来隐藏元素,而是使用toggleClass

SASS: 上海社会科学院:

.site-nav-wrapper.hidden {

    display: none;

    @include breakpoint($breakpoint-lg) {
        display: block;
    }
}

JS: JS:

$("header button").click(function(event){
    $(".site-nav-wrapper").toggleClass('hidden');
    event.preventDefault();
});

If I remember correctly toggle sets the display property to none on the element's style attribute. 如果我没记错, toggle在元素的style属性上将display属性设置为none If you want to force the button to display in the "desktop" orientation then you'll need to include an !important declaration in your desktop breakpoint. 如果要强制按钮以“桌面”方向显示,则需要在桌面断点中包含!important声明。

Alternately, you can listen for onorientationchanged and switch to the desktop version of the site then (un-toggling / activating everything that needs to be activated). 或者,您可以监听onorientationchanged并切换到站点的桌面版本(取消切换/激活需要激活的所有内容)。

Why not avoid the toggle so there's no issues with the media queries. 为什么不避免切换,所以媒体查​​询没有问题。

$("header button").click(function(event){
    $(".site-nav-wrapper:visible").hide();
    $(".site-nav-wrapper:hidden").show();
    event.preventDefault();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM