【问题标题】:Variation of image in JS [duplicate]JS中图像的变化[重复]
【发布时间】:2020-11-21 06:47:52
【问题描述】:

我试图自己解决问题,但我不知道。

当屏幕宽度减小或扩大时, 如何在JS中减小或增加图像的宽度?

【问题讨论】:

  • 在 CSS 中将宽度设置为百分比。以img {width: 100%} 为例。

标签: javascript html image width screen


【解决方案1】:

您不需要 Javascript 来执行此操作。这只能通过 CSS 完成,您需要将图像宽度设置为 100% 以使其在浏览器窗口调整大小时响应。当您调整浏览器窗口的大小时,它会自动根据图像宽度以相同的纵横比获取高度。

你需要这样写一个css代码:

img.img-responsive {
    width: 100%;
}

【讨论】:

  • 感谢您解决我的问题
【解决方案2】:

在css而不是js中使用窗口调整图像大小会容易得多。

如果你的图片看起来像这样:

<div class="Somediv">
    <img src="somesource" class="Someimage"></img>
</div>

您的 css 可能如下所示:

.Somediv {
    width: 50%; //the div will take up 50% of the parent element. You can use 50vw to scale by the width of the window
}

.Someimg {
    display: block;
    width: 100%;
}

如果你真的想通过 JS 来做到这一点,here 是 element.classList 上的官方文档,它将帮助你做你想做的事情。

【讨论】:

  • 感谢您解决我的问题
【解决方案3】:

我在表格中有一张图片,为了让它适应表格,我在我的 css 中使用了这个类:

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

【讨论】:

    猜你喜欢
    • 2022-01-24
    • 2016-12-25
    • 2022-01-05
    • 2019-02-20
    • 1970-01-01
    • 2014-07-23
    • 1970-01-01
    • 2018-05-02
    • 1970-01-01
    相关资源
    最近更新 更多