【问题标题】:set width and height properties of class for the loaded images为加载的图像设置类的宽度和高度属性
【发布时间】:2018-09-26 09:01:58
【问题描述】:

我有一个图像数组 images 有四个随机图像,

contents类css样式的背景图片每次点击按钮都会改变,有buildimagechangeImage

是否可以将加载到类 contents 中的每个 图像 设置宽度和高度 为 same 宽度和班级高度

如何实现?

var images = ['https://picsum.photos/200/300/?random', 'https://picsum.photos/200/300/?random', 'https://picsum.photos/200/300/?random'];
var index = 0;

function buildImage() {

    document.getElementById('content').style.backgroundImage = 'url('+images[index]+')';

}

function changeImage() {
    index++;
    if (index >= images.length) index = 0;
    document.getElementById('content').style.backgroundImage = 'url(' + images[index] + ')';
}
.contents {
    width: 70%;
    height: 50%;
    border: 2px solid #FF0000;
}
p{
color:#00FF00;}
<div class="contents" id="content"><p>set background image height ans width same as this box </p></div>
<button onclick="changeImage()">NextImage</button>

【问题讨论】:

  • 您可以使用background-size: 100% 100%; 简单地实现它 - 这就是您想要的吗?
  • 试试 background-size:cover;

标签: javascript html css


【解决方案1】:

您可以简单地使用 CSS 来缩放图像,将 background-size 设置为 100%:

background-size: 100% 100%;

这样,图像的缩放与其容器的尺寸完全相同。这是工作示例:

var images = ['https://picsum.photos/200/300/?random', 'https://picsum.photos/200/300/?random', 'https://picsum.photos/200/300/?random'];
var index = 0;

function buildImage() {

  document.getElementById('content').style.backgroundImage = 'url(' + images[index] + ')';

}

function changeImage() {
  index++;
  if (index >= images.length) index = 0;
  document.getElementById('content').style.backgroundImage = 'url(' + images[index] + ')';
}
.contents {
  width: 70%;
  height: 50%;
  border: 2px solid #FF0000;
  background-size: 100% 100%;
}

p {
  color: #00FF00;
}
<div class="contents" id="content">
  <p>set background image height ans width same as this box </p>
</div>
<button onclick="changeImage()">NextImage</button>

【讨论】:

  • 哦,我们必须在 css 中更正它,现在我明白了.. 感谢您的回复
  • 不客气!如果这篇文章对你有帮助,我很感激接受/赞成:)祝你有美好的一天!
  • 我非常喜欢这个
猜你喜欢
  • 1970-01-01
  • 2016-12-25
  • 2012-03-01
  • 2014-06-21
  • 1970-01-01
  • 2017-11-03
  • 1970-01-01
  • 2013-05-26
  • 2016-02-07
相关资源
最近更新 更多