【问题标题】:different CSS style class on page load for mobile and desktop [duplicate]移动和桌面页面加载的不同CSS样式类[重复]
【发布时间】:2019-05-14 14:25:37
【问题描述】:

我正在尝试为我的前端创建一个侧边栏菜单,该菜单应默认显示在桌面上,但在移动设备上开始隐藏。下面显示的“活动”类处理显示/隐藏之间的转换。侧边栏有效,当我点击手机上的“汉堡包”按钮时,它会按原样显示或隐藏菜单。

CSS:

.sidebar {
    transform: translateY(-100%);
    transition: all .25s ease-in-out;
}

.sidebar.active {
    transform: translateY(0);
    transition: all .25s ease-in-out;
}

JS:

$("#sidebar-toggle").click(function () {
    $(".sidebar").toggleClass("active");
});

默认情况下,桌面的菜单具有“活动”类,因此除非用户隐藏它,否则它会显示,当我在移动设备上加载页面后尝试隐藏菜单时会出现问题:

$(document).ready(function () {
    if ( window.innerWidth >= 770 )
    { $(".sidebar").addClass("active"); }
    else
    { $(".sidebar").removeClass("active"); }
});

但是,在手机上浏览应用程序时,您会看到每次刷新页面时菜单都会消失。如何在不使用 JS 的情况下将侧边栏设置为桌面上的“活动”,而不是移动设备上的默认状态?

更新:因为看起来有些人难以理解发生了什么,我将再次尝试澄清,现在只使用简单的句子:

我希望我的侧边栏默认在桌面上具有“活动”类(最小尺寸 > 770)。 我还希望我的侧边栏在移动设备上默认没有“活动”类(最小尺寸

UPDATE2:我真的希望这更容易理解:我想在桌面上创建带有“活动”类的侧边栏,但在移动设备上没有“活动”类。我不想从“活动”类开始,然后在页面加载后用 JS 将其删除,这就是我现在所做的。我希望侧边栏在没有活动课程的情况下开始 - 但仅在移动设备上。

【问题讨论】:

  • 不...我知道如何按尺寸定位屏幕,我不知道如何仅为特定尺寸应用 CSS 类(活动)
  • 不会使用媒体查询有效地将 CSS 类专门添加到该大小吗?示例:@media (max-width:500px) .sidebar.active { transform: translateY(0); transition: all .25s ease-in-out; } 仅适用于宽度小于 500 像素的设备
  • 您的问题是How can I set the sidebar to be 'active' on desktops, but not on mobile devices by default without using JS,该问题的答案已经存在。这被称为重复。没必要粗鲁。
  • @dream88 很有趣,但不起作用...
  • 不要责怪其他用户不理解你。他们为您提供了客户端解决方案,但没有什么能让您满意。因此,可能有两种方法:1. 问题无法解决(几乎) 2. 问题不在于前端。

标签: javascript jquery html css


【解决方案1】:
/* apply hide the element when width larger than 770px */    
@media (max-width: 770px) {
   .sidebar.active {
      display:none;
   }
}

【讨论】:

  • 欢迎来到 Stack Overflow!虽然这段代码 sn-p 可能是解决方案,但包含解释确实有助于提高帖子的质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
【解决方案2】:

有人早些时候发布了类似的内容,但删除了答案,经过一些修补后,我得到了这个工作。默认情况下,侧边栏没有设置“活动”类。同样默认情况下,它对于移动设备是隐藏的,但对于桌面设备是显示的。 'active' 类提供了在移动设备上显示侧边栏的能力。

/* small screen, hidden by default */
@media only screen and (max-width: 770px ) {
    .sidebar {
        transform: translateY(-100%);
        transition: all .25s ease-in-out;
    }
}

/* large screen, shown by default */
@media only screen and (min-width: 771px ) {
    .sidebar {
        transform: translateY(0);
        transition: all .25s ease-in-out;
    }
    #sidebar-toggle {
        display: none;
    }
}

/* activate the menu on small screen */
.sidebar.active {
    transform: translateY(0);
    transition: all .25s ease-in-out;
}

【讨论】:

    猜你喜欢
    • 2021-07-25
    • 2019-08-19
    • 1970-01-01
    • 2018-10-07
    • 1970-01-01
    • 2012-06-25
    • 1970-01-01
    • 1970-01-01
    • 2018-11-11
    相关资源
    最近更新 更多