首页 > 解决方案 > JavaScript:如何根据图像和父宽度按比例调整 div 大小?

问题描述

我正在用 ReactJS 开发一个应用程序。我有一个content editable div用户可以添加图片并在这些图片上写文字的地方。为了在用户添加图片时执行此操作,我将另一个内容可编辑 div 附加到可编辑的主要内容,并将背景设置为他选择的图片。这是它的截图:

在此处输入图像描述

(注意:仍在试图弄清楚为什么我在右侧得到额外的边距,并非所有图片都会发生这种情况;我想这与比例、舍入和从 100% 到像素的转换有关。检查下面的代码.) --> 编辑:这个问题是由 div 的边框 1px 引起的。我通过从图像宽度中删除 2px 来修复它。

为了调整 div 的大小并使其具有正确的大小,我在加载图片的地方添加了一个隐藏的图像标签,然后onload检索高度和宽度并相应地设置我的 div 大小,如下所示:

// here I create the div that will have the background image

let div = document.createElement('div');
div.setAttribute('contenteditable', 'true');
div.style.backgroundImage = 'url(' + image.webformatURL + ')';
div.style.backgroundSize = 'contain';
div.classList.add('text-page');

// here I create the image tag that will be invisible
// the css tells the image to have width: 100%, hence
// the picture will grow to fit the width

let img = document.createElement('img');
img.src = image.webformatURL;
img.classList.add('editor-thumb');

// here I add the image to the div

div.appendChild(img);

// here I append the div to the main content editable with id 'editor'

document.getElementById('editor').appendChild(div);

img.onload = () => {

    // once the image has loaded I set the div height and width

    // I believe that somehow this is where I get the extra margin mentioned above

    div.style.height = img.height + 'px';

    // fixing the extra margin here below

    div.style.width = (parseInt(img.width) - 2) + 'px';

    // then I get rid of the picture used to get height and width

    div.removeChild(img);
};

的CSS:

.text-page {
    background-size: contain;
    text-shadow: 0.075em 0.08em 0.1em rgba(0, 0, 0, 1);
    font-size: 30px;
    color: white;
    line-height: 90%;
    display: table-cell;
    vertical-align: middle;
}

.editor-thumb, .text-page {
    width: 100%;
    height: auto;
    box-shadow: var(--box-shadow);
    border: 1px solid var(--border-color);
    border-radius: var(--border-radius);
}

这是有效的,但我想知道是否有更好/更清洁的方法来做到这一点。任何帮助,将不胜感激。

标签: javascriptreactjscontenteditable

解决方案


推荐阅读