【问题标题】:how to set div height as background image?如何将div高度设置为背景图片?
【发布时间】:2023-02-01 02:50:54
【问题描述】:

我要实现的是DIV的高度会根据图像大小而变化(不重复)
我正在寻找具有广泛浏览器支持的解决方案,我已经尝试了几乎所有在 Google 上找到的答案,但没有任何效果

<!DOCTYPE html>
<html>
<head>
<style> 
#div_1 {
  width: 250px;
  height: 250px;
  background-image: url("https://i.ibb.co/YRwty0q/11.jpg");
}
#div_2 {
  width: 250px;
  height: 250px;
  background-image: url("https://i.ibb.co/khjZcj2/222.jpg");
}

</style>
</head>
<body>

<div id="div_1"></div>
<div id="div_2"></div>
<script>
  

</script>
</body>
</html>

【问题讨论】:

  • 为什么不只是 &lt;img&gt; 标签呢?

标签: javascript html css


【解决方案1】:

使用 Javascript 加载图像:

$('div').each(function() {
  const imageProp = getComputedStyle($(this)[0])['background-image']
  const url = imageProp.slice(imageProp.indexOf('"') + 1, imageProp.lastIndexOf('"'))
  const img = new Image()
  img.src = url
  img.onload = () => {
    $(this).css({
      width: img.width,
      height: img.height
    })
  }
})
#div_1 {
  background-image: url("https://i.ibb.co/YRwty0q/11.jpg");
}

#div_2 {
  background-image: url("https://i.ibb.co/khjZcj2/222.jpg");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div_1"></div>
<div id="div_2"></div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-14
    • 2015-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-20
    • 2015-07-08
    相关资源
    最近更新 更多