【问题标题】:Show content on screen size在屏幕大小上显示内容
【发布时间】:2014-04-27 15:44:28
【问题描述】:

我正在尝试创建一个横幅,其中包含 1 张幻灯片的 3 个版本,其中包含 1 张图片。

我知道如何使用 display: none 来做到这一点,但这意味着所有内容都已加载,它会影响慢速网络或移动设备的加载速度。

我不是 javascript 或 jquery wiz,所以越简单越好。

我想做的是:

屏幕分辨率高达 620 像素

{加载此 HTML }

屏幕分辨率 621px 到 920px

{ 加载此 HTML }

屏幕分辨率为 921 像素及以上

{ 加载此 HTML }

这可能吗?

【问题讨论】:

    标签: html show screen-size


    【解决方案1】:

    您可以使用 CSS 屏幕查询来处理此问题,但就像您说的那样,它将全部加载并隐藏它们。所以你必须走我认为的 JQuery 路线。

    【讨论】:

      【解决方案2】:

      我认为更好的方法是使用 CSS

      例如,让所有图像具有响应性:

      img {
          max-width: 100%;
          height: auto;
      }
      

      check the another tricks>>

      或者您可以通过 @media's 进行此操作:

      @media (max-width: 979px) {
      (css here - widths < 979)
      }
      
      @media all and (max-width: 767px) and (min-width: 400px) {
      (widths between 400 and 767)
      }
      
      @media all and (max-width: 399px) and (min-width: 0px) {
      (widths between 399-0px)
      }
      

      希望我能帮上忙。

      【讨论】:

      • 我知道 CSS 路线,我正在寻找一种无需加载所有 html 的方法。
      【解决方案3】:

      “这可能吗?”

      是的,但为了保持代码的简单性,您需要使用 不同的 方法:根据用户的屏幕宽度将用户发送到三个不同页面之一,而不是加载新的 div在同一页面中。我将逐步解释如何做到这一点。我们开始:

      如何使用 JavaScript 检查用户的屏幕宽度:

      if(window.innerWidth <= 620){
      // The window width is less or equal to 620px.
      }
      if(window.innerWidth > 620 && window.innerWidth <= 920){
      // The window width is greater than 620px and less or equal to 920px.
      }
      if(window.innerWidth > 920){
      // The window width is greater than 920px.
      }
      

      如果您将window.innerWidth 值存储在width 变量中,您还可以稍微简化此代码,如下所示:

      var width = window.innerWidth;
      

      然后你可以使用if(width &gt; 620){/* Code here */}来检查窗口宽度是否大于620px。

      现在您将创建两个或多个页面,每个页面都有一个修改,然后如果用户的屏幕尺寸为X,则将其发送到另一个页面。为此,您只需在上述ifs 中使用location.href="#"; 并将“#”替换为其他页面URL

      处理页面大小调整:

      以上代码是有关如何检查用户窗口宽度的示例,但浏览器将在页面加载时运行此代码,仅一次,但在调整大小时不会运行。要让这段代码在浏览器调整大小时运行,您需要将这些 ifs 包装在一个函数中并使用 EventListener 调用它,这将在调整浏览器大小时对代码说。


      最终代码结果:

      这是移植到函数的最终代码,在 EventListener 中调用并将用户发送到另一个页面:

      function checkWidth(){
      var width = window.innerWidth;
          if(width <= 620){
          location.href = "#"; // The window width is less or equal to 620px.
          }
          if(width > 620 && width <= 920){
          location.href = "#"; // The window width is greater than 620px and less or equal to 920px.
          }
          if(width > 920){
          location.href = "#"; // The window width is greater than 620px.
          }
      }
      
      window.addEventListener('resize', checkWidth);
      checkWidth();
      

      JSFiddle Demo

      【讨论】:

      • 谢谢你,我会试试这个方法,看看效果如何
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-08
      • 2018-03-30
      相关资源
      最近更新 更多