【问题标题】:How to force CSS @media style from JS regardless of screen size?无论屏幕大小如何,如何从 JS 强制 CSS @media 样式?
【发布时间】:2016-05-17 07:27:54
【问题描述】:

我的网站风格分为两部分:

@media only screen and (max-width: 725px)  {
    /* a lot of styles for small screens */
}

@media only screen and (min-width: 725px) {
    /* a lot of styles for big screens */
}

我有一种情况,我想强制使用小屏幕样式,尽管当前的屏幕尺寸更宽。所以,基本上,我想在桌面上强制使用移动外观。

请记住,我无法在 css 中更改太多内容,并且样式应保留在媒体查询中。

实现此目的的最佳方法是什么?我更喜欢使用 JavaScript 的解决方案。

【问题讨论】:

标签: javascript css html media-queries


【解决方案1】:

我不确定是否可以为不匹配的媒体强制呈现媒体查询样式。不过,我觉得你已经很清楚地提出了挑战,所以我有一个建议,你可以如何以我知道可行的方式解决问题。

按照 CSS 的工作方式,您编写的任何规则都将应用于所有匹配的元素,除非有更具体或更近期的内容覆盖它。

由于您知道您总是希望在移动设备上使用移动样式,因此通过从您的移动样式中删除媒体查询,您可以将移动演示设置为您的默认外观。

由于您知道您只有有时(即使“有时”实际上是“几乎总是”)希望桌面样式出现在更大的屏幕上,您可以设置自己的切换方式他们。对我来说,最简单的方法是在 body 标记和每个桌面声明的开头添加一个 ID。

//small screen styles
    /* a lot of styles for small screens */

//conditional wide-screen styles
@media only screen and (min-width: 725px) {
    #wideLayout //styles
    #wideLayout //styles
    #wideLayout //styles
}

按照这样安排的 CSS,只有当屏幕足够宽并且存在 ID 为 #wideLayout 的顶级父级时,才会应用宽屏样式。并且(根据要求)您可以使用 javascript 来切换这些样式,只需切换该 ID。

例子:

$('#toggleLayout').on('click',function(){
  if ($('section').attr('id') == "wideLayout"){
    $('section').attr('id','');
  } else {
    $('section').attr('id','wideLayout');
  }
});
/*small screen styles*/
  div {background-color:#484;display:inline-block;width:50px;height:50px;margin:10px;}
  
    
/*conditional wide-screen styles*/
/*I changed the query here so the preview window would be wide-enough to demonstrate*/
@media only screen and (min-width: 125px) {
    #wideLayout div {background-color:#848;display:block;width:auto;height:80px;margin:10px 0 0 0;}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<button id="toggleLayout">Toggle Layout</button>

<section>
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
  <div>7</div>
  <div>8</div>
</section>

这是一个 jsfiddle,您可以使用它来玩我的解决方案:https://jsfiddle.net/sq8jhu93/2/

【讨论】:

    猜你喜欢
    • 2023-03-22
    • 1970-01-01
    • 2015-10-03
    • 1970-01-01
    • 2014-12-27
    • 1970-01-01
    • 1970-01-01
    • 2016-09-08
    • 1970-01-01
    相关资源
    最近更新 更多