JavaScript: как пропорционально изменить размер div в зависимости от изображения и ширины родительского элемента? - PullRequest
0 голосов
/ 22 сентября 2019

Я разрабатываю приложение с ReactJS.У меня есть content editable div, где пользователь может добавлять картинки и писать текст на этих картинках.Чтобы сделать это, когда пользователь добавляет изображение, я добавляю другой редактируемый div содержимого к основному редактируемому контенту и устанавливаю фон для изображения, которое он выбрал.Это скриншот того, как это выглядит:

enter image description here

(Примечание: все еще пытаюсь выяснить, почему я получаю эту дополнительную маржу справа,Это происходит не со всеми изображениями; я полагаю, что это как-то связано с пропорциями, округлением и преобразованием от 100% до пикселей. Проверьте код ниже.) -> edit: эта проблема была вызвана границей 1px элемента div.Я исправил это, удалив 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);
}

Это работает, но мне интересно, есть ли способ лучше / чищечтобы сделать это. Любая помощь будет оценена.

...