javascript - 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);
}
这是有效的,但我想知道是否有更好/更清洁的方法来做到这一点。任何帮助,将不胜感激。
解决方案
推荐阅读
- javascript - 使用 AJAX POST/GET 方法解析 Base64 字符串时的未定义索引
- jquery - 有条件的切换类
- c# - 如果我不能在 C# 中调用析构函数,为了安全起见销毁对象的解决方案是什么?
- java - 滚动窗格中的 TextField 未正确显示
- macos - 如何使用 IOHIDManager 或蓝牙读取 iOS 键盘上的 home 键?
- php - incIude.php,在“l”位置用大写“i”拼写
- python - 纸浆和 OR-Tools 替代品
- search - 在 wooocmmerece 网站上应用无限滚动未按预期工作
- angular - 有 Promise 的 Jasmine 测试构造函数
- architecture - 架构:微服务、多重需求和共享数据