【问题标题】:i have div and i want to set div height dependent on background-image height我有 div,我想根据背景图像高度设置 div 高度
【发布时间】:2015-08-17 21:02:55
【问题描述】:

我有一个动态 JS 代码,可以在每次点击时更改 div 的背景图像。如何根据图像大小更改div 的高度和宽度?

这是我的代码以便更好地理解我的问题:

element.style {
    background: rgba(0, 0, 0, 0) url("../wp-content/uploads/ssf-wp-uploads/images/24/image.jpg") no-repeat scroll center center;
    cursor: pointer;
    height: 150px;
    position: relative;
}

在这里我设置了一个固定大小150px,但背景图像大小可以改变。所以我想根据背景图像高度设置div 高度。

【问题讨论】:

  • 更改 div 的大小可能会破坏页面的布局...您确定要这样做吗?
  • 实际上我正在处理地图并在单击每个标记后打开一个弹出信息..
  • 我不确定这意味着什么或它是如何相关的。您是否每次都打开不同的弹出窗口,每个窗口都有自己的 bg 图片?
  • 只使用 <img> 和背景图片的 url 怎么样?它会自动调整大小...(您仍然可以对其应用 css 过滤器和其他东西)
  • 是的,我在每个弹出窗口上更改 BG 图像。 BG 图像大小不固定。这就是我问的原因。看这里更清楚。

标签: javascript css


【解决方案1】:

既然您提到要让 div 高度自动调整为背景图像,请注意,背景图像对 div的大小没有影响> 它是在其中声明的。

div{
    background-image: url('http://www.pets4homes.co.uk/images/articles/1111/large/feline-influenza-all-about-cat-flu-5239fffd61ddf.jpg');
    background-size: contain;
    background-repeat: no-repeat;
    width: 100%;
    padding-top: 66.64%; /* (img-height / img-width * container-width) */
                /* (853 / 1280 * 100) */
}

这是使背景图像像 img 一样工作的技巧。为了更好地了解应该如何事先知道图像的大小,我建议在这里详细阅读作者的答案以及 cmets:How to get div height to auto-adjust to background size?

【讨论】:

    【解决方案2】:

    CSS

    .elementstyle{
            background-image: url('http://www.pets4homes.co.uk/images/articles/1111/large/feline-influenza-all-about-cat-flu-5239fffd61ddf.jpg');
            background-size: contain;
            background-repeat: no-repeat;
            background-size: contain;
    
    }
    

    在 jQuery 中:

    var img= $('img');
    
    img.removeAttr("width");
    img.removeAttr("height");
    
    var img_width = img.width();
    var img_height = img.height();
    
    $('.elementstyle').width(img_width).height(img_height);
    

    编辑:我刚刚注意到您要求从 CSS 中获取背景图像的大小。上面的方法将从以下位置获取属性:

    <div class="elementstyle"><img src=""/></div>
    

    您必须考虑在 jQuery 中定义背景图像的大小。 Here's some reading material.

    【讨论】:

    • 你能改变我的代码吗?其实我对css没有更多的了解
    • 完成。显然将 jQuery 包装在
    猜你喜欢
    • 1970-01-01
    • 2011-09-27
    • 2023-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-19
    相关资源
    最近更新 更多