В настоящее время, если пользователь несколько раз вставляет изображения в окно чата с помощью клавиш «ctrl» и «v», они располагаются вертикально. Ввод чата находится прямо над кнопкой «Выполнить». Над входом в чат отображаются загруженные изображения.
Сделайте так, чтобы загруженные несколько изображений располагались горизонтально (слева направо), если пользователь несколько раз вставляет изображения во входные данные чата.
В настоящее время загруженные несколько изображений располагаются вертикально.
document.addEventListener('DOMContentLoaded', () => {
const textInput = document.getElementById('textInput');
const imageContainer = document.getElementById('imageContainer');
const runButton = document.getElementById('runButton');
textInput.addEventListener('paste', (event) => {
const items = (event.clipboardData || window.clipboardData).items;
for (const item of items) {
if (item.type.indexOf('image') !== -1) {
const file = item.getAsFile();
const reader = new FileReader();
reader.onload = (event) => {
displayImage(event.target.result);
};
reader.readAsDataURL(file);
event.preventDefault();
}
}
});
function displayImage(src) {
const imgContainer = document.createElement('div');
imgContainer.classList.add('img-preview-container');
const img = document.createElement('img');
img.src = src;
img.classList.add('img-preview');
const removeButton = document.createElement('button');
removeButton.classList.add('remove-button');
removeButton.textContent = '✖';
removeButton.addEventListener('click', () => {
imgContainer.remove();
});
imgContainer.appendChild(img);
imgContainer.appendChild(removeButton);
imageContainer.appendChild(imgContainer);
}
runButton.addEventListener('click', () => {
console.info('Run button clicked');
});
});
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #181818;
}
.chat-container {
width: 80%;
max-width: 800px;
background-color: #2e2e2e;
border-radius: 10px;
padding: 10px;
color: #fff;
outline: 2px solid black; /* Added outline */
}
.input-container {
width: 100%;
min-height: 50px;
padding: 10px;
background-color: #1e1e1e;
border: 1px solid #444;
border-radius: 5px;
outline: none;
color: #fff;
margin-bottom: 10px;
}
.image-container {
display: flex;
flex-wrap: wrap;
gap: 10px;
width: 100%;
padding: 10px;
background-color: #1e1e1e;
border: 1px solid #444;
border-radius: 5px;
min-height: 50px;
margin-bottom: 10px;
}
.run-button {
margin-top: 10px;
padding: 10px;
background-color: #3b82f6;
border: none;
border-radius: 5px;
color: #fff;
cursor: pointer;
}
.run-button:hover {
background-color: #2563eb;
}
.img-preview-container {
position: relative;
display: inline-block;
}
.img-preview {
max-width: 100%;
border-radius: 5px;
}
.remove-button {
position: absolute;
top: 5px;
right: 5px;
background-color: #ff4d4d;
border: none;
border-radius: 50%;
color: white;
cursor: pointer;
width: 20px;
height: 20px;
font-size: 12px;
line-height: 20px;
text-align: center;
padding: 0;
}
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8" />
<meta name = "viewport" content = "width=device-width, initial-scale=1.0" />
<title>Chat Input with Image Paste</title>
<link rel = "stylesheet" href = "styles.css" />
</head>
<body>
<div class = "chat-container">
<div class = "image-container" id = "imageContainer"></div>
<div
class = "input-container"
contenteditable = "true"
id = "textInput"
placeholder = "Type something"
></div>
<button class = "run-button" id = "runButton">Run</button>
</div>
<script src = "script.js"></script>
</body>
</html>
Не могли бы вы еще раз проверить мой пост? Я обновил его, добавив изображение того, как он выглядит при запуске фрагмента кода. Я понятия не имею, почему у меня изображения складываются вертикально.
Попробуйте добавить атрибут flex-direction:row в тег body и посмотрите, изменится ли это что-нибудь.
Проблема в том, что по умолчанию элементы div вашего изображения имеют полную ширину на 100 %, даже если они являются элементами inline-block
. Вам нужно установить ширину каждого из них.
В моем примере я сделал это, динамически задав ширину каждого из них в зависимости от количества изображений: ${100/all_images.length-10}%
.
Я вычитал 10 дополнительных пикселей, чтобы учесть отступы и поля для этого примера, вместо того, чтобы пытаться вычислить это динамически.
const all_images = imageContainer.querySelectorAll('.img-preview-container');
all_images.forEach(img=>img.style.width=`${100/all_images.length-10}%`);
document.addEventListener('DOMContentLoaded', () => {
const textInput = document.getElementById('textInput');
const imageContainer = document.getElementById('imageContainer');
const runButton = document.getElementById('runButton');
textInput.addEventListener('paste', (event) => {
const items = (event.clipboardData || window.clipboardData).items;
for (const item of items) {
if (item.type.indexOf('image') !== -1) {
const file = item.getAsFile();
const reader = new FileReader();
reader.onload = (event) => {
displayImage(event.target.result);
};
reader.readAsDataURL(file);
event.preventDefault();
}
}
});
function displayImage(src) {
const imgContainer = document.createElement('div');
imgContainer.classList.add('img-preview-container');
const img = document.createElement('img');
img.src = src;
img.classList.add('img-preview');
const removeButton = document.createElement('button');
removeButton.classList.add('remove-button');
removeButton.textContent = '✖';
removeButton.addEventListener('click', () => {
imgContainer.remove();
});
imgContainer.appendChild(img);
imgContainer.appendChild(removeButton);
imageContainer.appendChild(imgContainer);
const all_images = imageContainer.querySelectorAll('.img-preview-container');
all_images.forEach(img=>img.style.width=`${100/all_images.length-10}%`);
}
runButton.addEventListener('click', () => {
console.info('Run button clicked');
});
});
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #181818;
}
.chat-container {
width: 80%;
max-width: 800px;
background-color: #2e2e2e;
border-radius: 10px;
padding: 10px;
color: #fff;
outline: 2px solid black; /* Added outline */
}
.input-container {
width: 100%;
min-height: 50px;
padding: 10px;
background-color: #1e1e1e;
border: 1px solid #444;
border-radius: 5px;
outline: none;
color: #fff;
margin-bottom: 10px;
}
.image-container {
display: flex;
flex-wrap: wrap;
gap: 10px;
width: 100%;
padding: 10px;
background-color: #1e1e1e;
border: 1px solid #444;
border-radius: 5px;
min-height: 50px;
margin-bottom: 10px;
}
.run-button {
margin-top: 10px;
padding: 10px;
background-color: #3b82f6;
border: none;
border-radius: 5px;
color: #fff;
cursor: pointer;
}
.run-button:hover {
background-color: #2563eb;
}
.img-preview-container {
position: relative;
display: inline-block;
}
.img-preview {
max-width: 100%;
border-radius: 5px;
}
.remove-button {
position: absolute;
top: 5px;
right: 5px;
background-color: #ff4d4d;
border: none;
border-radius: 50%;
color: white;
cursor: pointer;
width: 20px;
height: 20px;
font-size: 12px;
line-height: 20px;
text-align: center;
padding: 0;
}
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8" />
<meta name = "viewport" content = "width=device-width, initial-scale=1.0" />
<title>Chat Input with Image Paste</title>
<link rel = "stylesheet" href = "styles.css" />
</head>
<body>
<div class = "chat-container">
<div class = "image-container" id = "imageContainer"></div>
<div
class = "input-container"
contenteditable = "true"
id = "textInput"
placeholder = "Type something"
></div>
<button class = "run-button" id = "runButton">Run</button>
</div>
<script src = "script.js"></script>
</body>
</html>
Похоже, если я вставляю изображения несколько раз, размер каждого загруженного изображения уменьшается. Интересно, хочу ли я сохранить одинаковый размер загружаемых изображений независимо от количества вставленных изображений, мне следует просто поработать с частью ${100/all_images.length-10}%
?
У меня складывается горизонтально в Chrome и FF.