【问题标题】:Resizing an image based on browser size根据浏览器大小调整图像大小
【发布时间】:2018-06-19 05:03:21
【问题描述】:

我正在尝试根据用户浏览器窗口的大小调整我的 Square 空间网站(链接 here)上的背景图像大小。更具体地说,如果用户的窗口大小低于某个宽度,则图像会调整为更小的尺寸并保持其纵横比。

这似乎是一个常见问题。我已经挖掘了几个小时,似乎无法找到解决方案。我正在使用 JavaScript 来完成这项工作,但它无法完成。

请注意,我说的是与流体调整大小不同的东西(即使用百分比值)。

我已通过质量验证运行此代码,它返回时没有出现语法错误。所以除此之外,我迷路了。

我将这个 (jQuery) 脚本注入到页眉中:

$(document).ready(function() {
    function imageresize() {
        var contentwidth = $(window).width();
        if ((contentwidth) < 1500) {
            $(".widescreen").attr("height", "480px");
        } else {
            $(".widescreen").attr("height", "768px");
        }
    }
    imageresize(); //Triggers when document first loads    

    $(window).on("resize", function() {
        imageresize();
    });
});
.widescreen {
  background: url(https://i.imgur.com/96pxGnd.jpg) center top no-repeat;
  background-size: cover;
  width: 100vw;
  position: relative;
  left: 50%;
  right: 50%;
  margin-left: -50vw;
  margin-right: -50vw;
  height: 768px;
  /* Trying to change this value so the rest of the CSS adjusts accordingly */
}
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

语法错了吗?请帮忙!并提前感谢您。

【问题讨论】:

标签: javascript jquery html css


【解决方案1】:

浏览器识别的div没有高度属性,所以

$(".widescreen").attr("height", "480px");

正在将 height="480px" 添加到代码中,但这并不能告诉它以不同的方式呈现。

我想你想要

$(".widescreen").css("height", "480px");

【讨论】:

  • 天哪,这太有道理了!更好的是:它奏效了!非常感谢!
【解决方案2】:

你应该使用 css 媒体查询来检查屏幕大小,然后设置你想要的样式here 是一个很好的教程,你也可以使用 bootstrap img-responsive 类它更容易使用here 你可以找到一个例子

【讨论】:

    【解决方案3】:

    为此尝试media screen

    @media screen and (min-width: 0px) and (max-device-width: 900px) {
      .image {
         width: 200px
      }
    }
    
    @media screen and (min-width: 900px) {
      .image {
         width: 500px
      }
    }
    <html>
      <header>
        <meta name="viewport" content="width=device-width, maximum-scale=1.0, minimum-scale=0.5,user-scalable=yes,initial-scale=1.0" />
      </header>
      <body>
        <img class="image" src="https://static.bhphotovideo.com/explora/sites/default/files/Correct.jpg" />
      </body>
    </html>

    【讨论】:

      【解决方案4】:

      可以使用CSS 中的以下代码sn-p 解决此问题,因为图像最好使用max-width 属性。此标记将使用百分比值作为图像的宽度。

      请补充,

      img {max-width:100%};
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-20
        • 2013-02-13
        • 2013-04-19
        • 2016-01-22
        • 1970-01-01
        • 1970-01-01
        • 2013-12-12
        • 2017-07-25
        相关资源
        最近更新 更多