1
Тестовая темка
Страница: 1
Сообщений 1 страница 3 из 3
Поделиться22025-08-15 15:05
Код:
<!--HTML-->
<style>
.earn-button {
margin: 0 3px;
background: #88a3ac;
color: #e0e0e0;
border: none;
cursor: pointer;
padding: 4px 8px;
font-size: 11px;
transition: all 0.2s ease;
border-radius: 4px;
font-weight: bold;
min-width: 24px;
text-align: center;
}
.earn-button:hover {
background: #bbabb5;
transform: scale(1.05);
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
.modal {
display: none;
position: fixed;
z-index: 1000;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
}
.modal-content {
background-color: #cccccc;
border: 1px solid #aaaaaa;
margin: 5% auto;
padding: 25px;
border-radius: 12px;
width: 80%;
max-width: 600px;
max-height: 80vh;
overflow-y: auto;
color: #e0e0e0;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
overflow: hidden;
}
.close {
color: #212121;
float: right;
font-size: 28px;
font-weight: bold;
cursor: pointer;
}
.close:hover {
color: #000000;
}
.modal h3,
.preview-header,
.preview-total,
.preview-total-balance,
.submit-btn,
.finish-btn {
color: #88a3ac;
font-family: "Quicksand", "Helvetica Neue", sans-serif;
}
.modal-title {
font-size: 20px !important;
color: #88a3ac !important;
margin-bottom: 5px !important;
margin-left: 0 !important;
margin-right: 0 !important;
background: transparent !important;
}
.form-group label {
display: block;
margin-bottom: 5px;
font-weight: bold;
color: #505050;
}
.form-group input,
.form-group textarea {
width: 100%;
padding: 10px;
border: 1px solid #aaaaaa;
border-radius: 6px;
background-color: #bbbbbb;
color: #e0e0e0;
font-family: "Quicksand", "Helvetica Neue", sans-serif;
box-sizing: border-box;
transition: all 0.2s ease;
}
.form-group input:focus,
.form-group textarea:focus {
outline: none;
border-color: #88a3ac;
box-shadow: 0 0 0 2px rgba(136, 163, 172, 0.2);
background-color: #c0c0c0;
}
.add-field-btn,
.remove-field-btn {
background: #88a3ac;
color: #e0e0e0;
border: none;
border-radius: 4px;
width: 30px;
height: 28px;
font-size: 18px;
font-weight: bold;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
transition: all 0.2s ease;
}
.add-field-btn:hover {
background: #bbabb5;
}
.remove-field-btn {
background: #dc3545;
}
.remove-field-btn:hover {
background: #c82333;
}
.submit-btn,
.finish-btn {
background: #88a3ac;
color: #e0e0e0;
border: none;
padding: 12px 24px;
border-radius: 6px;
cursor: pointer;
font-size: 14px;
font-weight: bold;
transition: all 0.2s ease;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.submit-btn:hover,
.finish-btn:hover {
background: #bbabb5;
transform: translateY(-1px);
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}
.info-text {
background: #d8d8d8;
padding: 15px;
border-radius: 6px;
border-left: 4px solid #88a3ac;
margin: 10px 0;
color: #7e7e7e;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}
#selected-items-preview {
background: #d8d8d8;
border: 1px solid #aaaaaa;
border-radius: 10px;
padding: 20px;
margin: 20px 0;
max-height: 300px;
overflow-y: auto;
box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.1);
}
.preview-empty {
color: #c7c7c7;
text-align: center;
font-style: italic;
padding: 20px;
}
.preview-item {
background: #bbbbbb;
border: 1px solid #aaaaaa;
border-radius: 6px;
padding: 12px;
margin-bottom: 10px;
transition: all 0.2s ease;
position: relative;
}
.preview-item:hover {
background: #c0c0c0;
transform: translateY(-1px);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.preview-item-header {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 5px;
}
.preview-item-number {
color: #88a3ac;
font-weight: bold;
min-width: 20px;
}
.preview-item-name {
color: #e0e0e0;
flex: 1;
}
.preview-item-amount {
color: #88a3ac;
font-weight: bold;
}
.preview-item-details {
color: #c7c7c7;
font-size: 12px;
margin-left: 30px;
word-break: break-word;
}
.preview-item-actions button {
background: none;
border: none;
color: #dc3545;
font-size: 14px;
cursor: pointer;
}
.bk-main-all {
display: flex;
gap: 20px;
margin-top: 20px;
}
.bk-main-all-left,
.bk-main-all-right {
flex: 1;
background: rgba(200, 200, 200, 0.1);
border-radius: 8px;
padding: 15px;
border: 1px solid rgba(136, 163, 172, 0.3);
}
.bk-main-all-left-tit {
font-weight: bold;
color: #88a3ac;
font-size: 16px;
margin-bottom: 15px;
text-align: center;
text-transform: uppercase;
letter-spacing: 1px;
border-bottom: 2px solid #88a3ac;
padding-bottom: 8px;
}
.bk-main-all-line p {
display: grid !important;
grid-template-columns: 1fr 60px 30px !important;
align-items: center !important;
gap: 7px !important;
margin: 2px 0 !important;
padding: 4px !important;
background: rgba(255, 255, 255, 0.05);
border-radius: 4px;
border-left: 2px solid transparent;
transition: all 0.2s ease;
}
.bk-main-all-line p:hover {
background: rgba(136, 163, 172, 0.1);
transform: translateX(1px);
}
.free-change {
grid-column: 2 / 4;
text-align: right;
color: #e0e0e0;
font-style: italic;
}
.bk-main-all-line p span {
text-align: right;
color: #88a3ac;
font-weight: bold;
font-size: 14px;
}
.modalContent h3 {
margin: 0 !important;
}
.field-row {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 10px;
}
.earnForm {
display: flex;
flex-direction: column;
gap: 10px;
}
</style>
<!-- Основной контент банка -->
<div class="fon">
<div class="bac">
<div class="namet">
<div class="bacname">банк</div>
</div>
</div>
</div>
<!-- Основной контент банка -->
<div class="bk-main-all">
<div class="bk-main-all-left">
<div class="bk-main-all-left-tit">заработать</div>
<div class="bk-main-all-line">
<p>100 сообщений <span>50</span><button class="earn-button" data-type="messages-100">+</button></p>
<p>100 позитива <span>20</span><button class="earn-button" data-type="positivity-100">+</button></p>
<p>100 репутации <span>20</span><button class="earn-button" data-type="reputation-100">+</button></p>
<p>заявка в нужные <span>50</span><button class="earn-button" data-type="application-needed">+</button></p>
<p>
заявка в хочу видеть <span>25</span><button class="earn-button" data-type="application-want">+</button>
</p>
<p>
забрать игрока из «хочу к вам» <span>15</span
><button class="earn-button" data-type="take-player">+</button>
</p>
<p>
привести на форум друга <span>45</span><button class="earn-button" data-type="bring-friend">+</button>
</p>
<p>
прийти по заявке <span>20</span><button class="earn-button" data-type="come-by-application">+</button>
</p>
<p>1 реклама <span>5</span><button class="earn-button" data-type="advertisement">+</button></p>
<p>50 реклам <span>350</span><button class="earn-button" data-type="advertisement-50">+</button></p>
<p>заполненная анкета <span>75</span><button class="earn-button" data-type="filled-profile">+</button></p>
<p>игровой пост <span>50</span><button class="earn-button" data-type="game-post">+</button></p>
<p>
5 часов непрерывного онлайна [скрин] <span>70</span
><button class="earn-button" data-type="online-5hours">+</button>
</p>
<p>создали тему флуда <span>10</span><button class="earn-button" data-type="flood-topic">+</button></p>
<p>
участие в конкурсе <span>20</span
><button class="earn-button" data-type="contest-participation">+</button>
</p>
</div>
</div>
<div class="bk-main-all-right">
<div class="bk-main-all-left-tit">потратить</div>
<div class="bk-main-all-line">
<p>
выкупить внешность «нужного» на 2 недели <span>300</span
><button class="earn-button" data-type="buyout-needed-appearance">+</button>
</p>
<p>
выкупить внешность для себя на 2 недели <span>400</span
><button class="earn-button" data-type="buyout-self-appearance">+</button>
</p>
<p>
реклама с нужным до конца теста + неделя после <span>350</span
><button class="earn-button" data-type="needed-advertisement">+</button>
</p>
<p>
гифка в стиле форума от амс <span>100</span><button class="earn-button" data-type="forum-gif">+</button>
</p>
<p>
аватар от амс в цвет чистовика <span>1000</span
><button class="earn-button" data-type="custom-avatar">+</button>
</p>
</div>
</div>
</div>
<!-- Модальное окно -->
<div id="earnModal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<div id="modalContent"></div>
</div>
</div>
<!-- Предварительный просмотр выбранных пунктов -->
<div id="selected-items-preview">
<div class="preview-empty">Выберите пункты для заработка</div>
</div>
<!-- Кнопка "Закончить" -->
<div style="text-align: center; margin: 30px 0">
<button id="finishBtn" class="finish-btn" style="display: none">Закончить</button>
</div>
<script>
document.addEventListener("DOMContentLoaded", function () {
console.log("DOMContentLoaded");
console.log(0);
// Данные для модальных окон
const modalData = {
"messages-100": {
title: "100 сообщений",
description: "Укажите количество раз, когда вы достигли 100 сообщений",
fields: [
{
name: "count",
label: "Количество раз (например: 2 для 200 сообщений)",
type: "number",
required: true
}
]
},
"positivity-100": {
title: "100 позитива",
description: "Укажите количество раз, когда вы достигли 100 позитива",
fields: [
{
name: "count",
label: "Количество раз (например: 2 для 200 позитива)",
type: "number",
required: true
}
]
},
"reputation-100": {
title: "100 репутации",
description: "Укажите количество раз, когда вы достигли 100 репутации",
fields: [
{
name: "count",
label: "Количество раз (например: 2 для 200 репутации)",
type: "number",
required: true
}
]
},
"application-needed": {
title: "Заявка в нужные",
description: "Укажите ссылку на заявку (можно добавить несколько)",
fields: [{ name: "application_link", label: "Ссылка на заявку", type: "text", required: true }]
},
"application-want": {
title: "Заявка в хочу видеть",
description: "Укажите ссылку на заявку (можно добавить несколько)",
fields: [{ name: "application_link", label: "Ссылка на заявку", type: "text", required: true }]
},
"take-player": {
title: "Забрать игрока из «хочу к вам»",
description: "Укажите ссылку на ваше сообщение из темы (можно добавить несколько)",
fields: [{ name: "message_link", label: "Ссылка на сообщение", type: "text", required: true }]
},
"bring-friend": {
title: "Привести на форум друга",
description: "Укажите имя друга и подтверждение (можно добавить несколько имен)",
fields: [{ name: "friend_name", label: "Имя друга", type: "text", required: true }]
},
"come-by-application": {
title: "Прийти по заявке",
description: "Укажите ссылку на заявку",
fields: [{ name: "application_link", label: "Ссылка на заявку", type: "text", required: true }]
},
advertisement: {
title: "1 реклама",
description: "Укажите количество оставленных реклам",
fields: [{ name: "count", label: "Количество реклам", type: "number", required: true }]
},
"advertisement-50": {
title: "50 реклам",
description: "Никаких дополнительных данных не требуется",
fields: []
},
"filled-profile": {
title: "Заполненная анкета",
description: "Укажите ссылку на анкету (можно добавить несколько)",
fields: [{ name: "profile_link", label: "Ссылка на анкету", type: "text", required: true }]
},
"game-post": {
title: "Игровой пост",
description: "Укажите ссылку на пост (можно добавить несколько)",
fields: [{ name: "post_link", label: "Ссылка на пост", type: "text", required: true }]
},
"online-5hours": {
title: "5 часов непрерывного онлайна",
description: "Приложите скриншот онлайна",
fields: [{ name: "screenshot_link", label: "Ссылка на скриншот", type: "text", required: true }]
},
"flood-topic": {
title: "Создали тему флуда",
description: "Укажите ссылку на тему (можно добавить несколько)",
fields: [{ name: "topic_link", label: "Ссылка на тему", type: "text", required: true }]
},
"contest-participation": {
title: "Участие в конкурсе",
description: "Укажите ссылку на участие в конкурсе (можно добавить несколько)",
fields: [{ name: "contest_link", label: "Ссылка на участие", type: "text", required: true }]
},
// Данные для раздела "потратить"
"buyout-needed-appearance": {
title: "Выкупить внешность «нужного» на 2 недели",
description: "Укажите конкретную внешность из нужных",
fields: [{ name: "appearance_name", label: "Имя внешности", type: "text", required: true }]
},
"buyout-self-appearance": {
title: "Выкупить внешность для себя на 2 недели",
description: "Укажите конкретную внешность",
fields: [{ name: "appearance_name", label: "Имя внешности", type: "text", required: true }]
},
"needed-advertisement": {
title: "Реклама с нужным до конца теста + неделя после",
description: "Укажите описание и ссылку на заявку нужного",
fields: [
{ name: "description", label: "Описание", type: "textarea", required: true },
{ name: "application_link", label: "Ссылка на заявку нужного", type: "text", required: true }
]
},
"forum-gif": {
title: "Гифка в стиле форума от амс",
description: "Укажите описание желаемой гифки",
fields: [{ name: "gif_description", label: "Описание гифки", type: "textarea", required: true }]
},
"custom-avatar": {
title: "Аватар от амс в цвет чистовика",
description: "Укажите описание желаемого аватара и цветовые предпочтения",
fields: [
{ name: "avatar_description", label: "Описание аватара и цвета", type: "textarea", required: true }
]
}
};
console.log("modalData", modalData);
// Переменные для отслеживания выбранных пунктов
let selectedItems = [];
let currentBalance = 0;
let initialBalance = 0;
// Функция для получения начального баланса из UserFld3
function getInitialBalance() {
try {
// Пытаемся получить значение UserFld3
if (typeof UserFld3 !== "undefined" && UserFld3) {
// Убираем пробелы и преобразуем в число
const cleanValue = UserFld3.toString().replace(/\s/g, "");
const balance = parseInt(cleanValue);
return isNaN(balance) ? 0 : balance;
}
} catch (e) {
console.log("UserFld3 не доступна:", e);
}
return 0;
}
// Функция для получения суммы по типу
function getAmountForType(type) {
const amounts = {
"messages-100": 50,
"positivity-100": 20,
"reputation-100": 20,
"application-needed": 50,
"application-want": 25,
"take-player": 15,
"bring-friend": 45,
"come-by-application": 20,
advertisement: 5,
"advertisement-50": 350,
"filled-profile": 75,
"game-post": 50,
"online-5hours": 70,
"flood-topic": 10,
"contest-participation": 20,
// Суммы для раздела "потратить"
"buyout-needed-appearance": -300,
"buyout-self-appearance": -400,
"needed-advertisement": -350,
"forum-gif": -100,
"custom-avatar": -1000
};
return amounts[type] || 0;
}
console.log(1);
// Функция для добавления пункта в список
function addItem(type, details = "") {
console.log("type", type);
console.log("details", details);
const data = modalData[type];
console.log("data", data);
if (!data) return;
// Находим базовую сумму для этого пункта
const baseAmount = getAmountForType(type);
console.log("baseAmount", baseAmount);
// Проверяем, есть ли количество в details
let amount = baseAmount;
let displayName = data.title;
// Ищем количество в details для определенных типов
const quantityTypes = ["advertisement", "messages-100", "positivity-100", "reputation-100"];
if (quantityTypes.includes(type) && details) {
const countMatch = details.match(/:\s*(\d+)$/i);
console.log("countMatch", countMatch);
if (countMatch) {
const count = parseInt(countMatch[1]);
console.log("count", count);
if (count > 0) {
amount = baseAmount * count;
displayName = data.title + " (x" + count + ")";
console.log("amount", amount);
console.log("displayName", displayName);
}
}
}
// Обработка множественных значений для остальных типов
const multipleValueTypes = [
"application-needed",
"application-want",
"take-player",
"bring-friend",
"come-by-application",
"filled-profile",
"game-post",
"online-5hours",
"flood-topic",
"contest-participation"
];
if (multipleValueTypes.includes(type) && details) {
// Ищем количество значений в details
const fieldMatch = details.match(/:\s*([^,]+(?:,\s*[^,]+)*)/);
if (fieldMatch) {
const values = fieldMatch[1]
.split(",")
.map((item) => item.trim())
.filter((item) => item.length > 0);
if (values.length > 0) {
amount = baseAmount * values.length;
displayName = data.title + " (x" + values.length + ")";
}
}
}
selectedItems.push({
name: displayName,
amount: amount,
details: details
});
currentBalance += amount;
updatePreview();
}
console.log(2);
// Функция для добавления нового поля
function addField(fieldName) {
var container = document.getElementById(fieldName + "_container");
var fieldCount = container.children.length;
var newFieldRow = document.createElement("div");
newFieldRow.className = "field-row";
var input = document.createElement("input");
input.type = "text";
input.id = fieldName + "_" + fieldCount;
input.name = fieldName;
var removeBtn = document.createElement("button");
removeBtn.type = "button";
removeBtn.className = "remove-field-btn";
removeBtn.innerHTML = "-";
removeBtn.onclick = function () {
container.removeChild(newFieldRow);
};
newFieldRow.appendChild(input);
newFieldRow.appendChild(removeBtn);
container.appendChild(newFieldRow);
}
// Функция для удаления пункта
function removeItem(index) {
if (index >= 0 && index < selectedItems.length) {
currentBalance -= selectedItems[index].amount;
selectedItems.splice(index, 1);
updatePreview();
}
}
// Функция для обновления предварительного просмотра
function updatePreview() {
const previewContainer = document.getElementById("selected-items-preview");
const finishBtn = document.getElementById("finishBtn");
if (!previewContainer) return;
if (selectedItems.length === 0) {
previewContainer.style.display = "none";
if (finishBtn) finishBtn.style.display = "none";
return;
}
previewContainer.style.display = "block";
if (finishBtn) finishBtn.style.display = "inline-block";
// Разделяем пункты на заработки и траты
const earnings = selectedItems.filter((item) => item.amount > 0);
const expenses = selectedItems.filter((item) => item.amount < 0);
let previewHTML = '<div class="preview-header">Выбранные пункты:</div>';
let totalAmount = 0;
// Отображаем заработки
if (earnings.length > 0) {
previewHTML +=
'<div class="preview-section-title" style="color: var(--accent); font-weight: bold; margin: 10px 0 5px 0;">Заработки:</div>';
earnings.forEach(function (item, index) {
totalAmount += item.amount;
previewHTML += '<div class="preview-item">';
previewHTML += '<div class="preview-item-header">';
previewHTML += '<span class="preview-item-number">' + (index + 1) + ".</span>";
previewHTML += '<span class="preview-item-name">' + item.name + "</span>";
previewHTML +=
'<span class="preview-item-amount" style="color: var(--accent);">+' + item.amount + "</span>";
previewHTML += '<div class="preview-item-actions">';
previewHTML +=
'<button type="button" class="remove-item-btn" data-index="' +
selectedItems.indexOf(item) +
'">❌</button>';
previewHTML += "</div>";
previewHTML += "</div>";
previewHTML += "</div>";
});
}
// Отображаем траты
if (expenses.length > 0) {
if (earnings.length > 0) {
previewHTML += '<div style="margin: 10px 0;"></div>';
}
previewHTML +=
'<div class="preview-section-title" style="color: #dc3545; font-weight: bold; margin: 10px 0 5px 0;">Траты:</div>';
expenses.forEach(function (item, index) {
totalAmount += item.amount;
previewHTML += '<div class="preview-item">';
previewHTML += '<div class="preview-item-header">';
previewHTML += '<span class="preview-item-number">' + (earnings.length + index + 1) + ".</span>";
previewHTML += '<span class="preview-item-name">' + item.name + "</span>";
previewHTML +=
'<span class="preview-item-amount" style="color: #dc3545;">' + item.amount + "</span>";
previewHTML += '<div class="preview-item-actions">';
previewHTML +=
'<button type="button" class="remove-item-btn" data-index="' +
selectedItems.indexOf(item) +
'">❌</button>';
previewHTML += "</div>";
previewHTML += "</div>";
previewHTML += "</div>";
});
}
const totalBalance = initialBalance + totalAmount;
previewHTML += '<div class="preview-total">Итого: <strong>' + totalAmount + "</strong></div>";
previewHTML +=
'<div class="preview-total-balance">Общий баланс: <strong>' + totalBalance + "</strong></div>";
previewContainer.innerHTML = previewHTML;
}
// Функция для обновления шаблона в textarea
function updateTemplate() {
const textarea = document.getElementById("main-reply");
if (!textarea) return;
// Если ничего не выбрано, не заполняем textarea
if (selectedItems.length === 0) {
textarea.value = "";
return;
}
// Разделяем пункты на заработки и траты
const earnings = selectedItems.filter((item) => item.amount > 0);
const expenses = selectedItems.filter((item) => item.amount < 0);
let template = "";
// Добавляем секцию заработков, если есть
if (earnings.length > 0) {
template += "[b]1. за что + доказательства[/b]\n";
earnings.forEach(function (item, index) {
template += index + 1 + ". " + item.name + " - " + item.amount + "\n";
if (item.details) {
template += " " + item.details + "\n";
}
template += "\n";
});
}
// Добавляем секцию трат, если есть
if (expenses.length > 0) {
if (earnings.length > 0) {
template += "\n";
}
template += "[b]2. на что потратить[/b]\n";
expenses.forEach(function (item, index) {
template += index + 1 + ". " + item.name + " - " + Math.abs(item.amount) + "\n";
if (item.details) {
template += " " + item.details + "\n";
}
template += "\n";
});
}
template += "[b]3. расчет[/b]\n";
const totalBalance = initialBalance + currentBalance;
template += initialBalance + " + " + currentBalance + " = [b]" + totalBalance + "[/b]";
textarea.value = template;
}
console.log(3);
// Функция для завершения заполнения
function finishTemplate() {
const textarea = document.getElementById("main-reply");
if (!textarea) return;
// Генерируем полный шаблон
updateTemplate();
// Разделяем пункты на заработки и траты
const earnings = selectedItems.filter((item) => item.amount > 0);
const expenses = selectedItems.filter((item) => item.amount < 0);
// Добавляем финальную информацию
let finalTemplate = textarea.value;
const totalBalance = initialBalance + currentBalance;
if (earnings.length > 0) {
const totalEarnings = earnings.reduce((sum, item) => sum + item.amount, 0);
finalTemplate += "\n\n[b]Итого заработано: " + totalEarnings + "[/b]";
}
if (expenses.length > 0) {
const totalExpenses = Math.abs(expenses.reduce((sum, item) => sum + item.amount, 0));
finalTemplate += "\n[b]Итого потрачено: " + totalExpenses + "[/b]";
}
finalTemplate += "\n[b]Общий баланс: " + totalBalance + "[/b]";
textarea.value = finalTemplate;
// Скроллим к textarea
textarea.scrollIntoView({ behavior: "smooth", block: "center" });
// Фокусируемся на textarea
textarea.focus();
// Очищаем список выбранных пунктов
selectedItems = [];
currentBalance = 0;
// Очищаем предварительный просмотр (это также скроет кнопку)
updatePreview();
}
console.log(4);
// Функция закрытия модального окна
function closeModal() {
document.getElementById("earnModal").style.display = "none";
}
console.log(5);
// Функция открытия модального окна
function openModal(type) {
const modal = document.getElementById("earnModal");
const modalContent = document.getElementById("modalContent");
const data = modalData[type];
if (!data) return;
var fieldsHTML = "";
if (data.fields.length !== 0) {
fieldsHTML = data.fields
.map(function (field) {
var fieldHTML = '<div class="form-group">';
fieldHTML += '<label for="' + field.name + '">' + field.label + ":</label>";
if (field.type === "textarea") {
fieldHTML += '<textarea id="' + field.name + '" name="' + field.name + '"';
if (field.required) fieldHTML += " required";
fieldHTML += "></textarea>";
} else {
// Проверяем, является ли это полем количества
const isQuantityField =
field.name === "count" ||
field.name === "positivity_count" ||
field.name === "reputation_count";
if (isQuantityField) {
// Для полей количества используем обычный input без кнопок
fieldHTML +=
'<input type="' +
field.type +
'" id="' +
field.name +
'" name="' +
field.name +
'"';
if (field.required) fieldHTML += " required";
fieldHTML += ">";
} else {
// Создаем контейнер для динамических полей
fieldHTML += '<div id="' + field.name + '_container">';
fieldHTML += '<div class="field-row">';
fieldHTML +=
'<input type="' +
field.type +
'" id="' +
field.name +
'_0" name="' +
field.name +
'"';
if (field.required) fieldHTML += " required";
fieldHTML += ">";
fieldHTML +=
'<button type="button" class="add-field-btn" data-field="' +
field.name +
'">+</button>';
fieldHTML += "</div>";
fieldHTML += "</div>";
}
}
fieldHTML += "</div>";
return fieldHTML;
})
.join("");
}
modalContent.innerHTML =
"<h3 class='modal-title'>" +
data.title +
"</h3>" +
'<div class="info-text">' +
data.description +
"</div>" +
'<form id="earnForm">' +
fieldsHTML +
'<button type="submit" class="submit-btn">Добавить</button>' +
"</form>";
modal.style.display = "block";
// Обработчик отправки формы
document.getElementById("earnForm").addEventListener("submit", function (e) {
e.preventDefault();
// Собираем данные из формы
let details = "";
if (data.fields.length !== 0) {
const fieldValues = [];
data.fields.forEach(function (field) {
if (field.type === "textarea") {
const value = document.getElementById(field.name).value;
if (value) {
fieldValues.push(field.label + ": " + value);
}
} else {
// Проверяем, является ли это полем количества
const isQuantityField =
field.name === "count" ||
field.name === "positivity_count" ||
field.name === "reputation_count";
if (isQuantityField) {
// Для полей количества берем значение напрямую
const value = document.getElementById(field.name).value;
if (value) {
fieldValues.push(field.label + ": " + value);
}
} else {
// Собираем все значения из динамических полей
const container = document.getElementById(field.name + "_container");
const inputs = container.querySelectorAll('input[name="' + field.name + '"]');
const values = [];
inputs.forEach(function (input) {
if (input.value.trim()) {
values.push(input.value.trim());
}
});
if (values.length > 0) {
fieldValues.push(field.label + ": " + values.join(", "));
}
}
}
});
details = fieldValues.join(", ");
}
// Добавляем пункт в список
addItem(type, details);
// Показываем кнопку "Закончил"
const finishBtn = document.getElementById("finishBtn");
if (finishBtn) {
finishBtn.style.display = "inline-block";
}
closeModal();
});
}
console.log(6);
// Инициализация при загрузке страницы
console.log("object 1234");
// Добавляем обработчики событий для всех кнопок
const earnButtons = document.querySelectorAll(".earn-button");
console.log("earnButtons", earnButtons);
earnButtons.forEach(function (button) {
console.log("button", button);
button.addEventListener("click", function () {
const type = this.getAttribute("data-type");
console.log("type", type);
if (type) {
openModal(type);
}
});
});
// Добавляем обработчик для кнопки закрытия модального окна
const closeButton = document.querySelector(".close");
console.log("closeButton", closeButton);
if (closeButton) {
closeButton.addEventListener("click", closeModal);
}
// Закрытие модального окна при клике вне его
window.addEventListener("click", function (event) {
const modal = document.getElementById("earnModal");
if (event.target === modal) {
closeModal();
}
});
// Добавляем обработчик для кнопки "Закончил"
const finishBtn = document.getElementById("finishBtn");
console.log("finishBtn", finishBtn);
if (finishBtn) {
finishBtn.addEventListener("click", finishTemplate);
}
// Добавляем делегирование событий для кнопок добавления полей
document.addEventListener("click", function (event) {
if (event.target.classList.contains("add-field-btn")) {
const fieldName = event.target.getAttribute("data-field");
if (fieldName) {
addField(fieldName);
}
}
// Обработка кнопки удаления пунктов
if (event.target.classList.contains("remove-item-btn")) {
const index = parseInt(event.target.getAttribute("data-index"));
removeItem(index);
}
});
// Инициализируем начальный баланс
initialBalance = getInitialBalance();
// Инициализируем предварительный просмотр (скроет элементы если ничего не выбрано)
updatePreview();
});
</script>
[hideprofile]
Поделиться32025-08-15 17:54
Код:
<!--HTML-->
<style>
.main-container {
width: 877px;
margin: 0 auto;
padding: 15px;
}
.carousel-section {
position: relative;
}
.carousel-header {
background: rgb(255 255 255 / 35%);
padding: 12px 10px 10px;
margin-bottom: 15px;
position: relative;
text-align: center;
}
.carousel-header::before {
content: "доступные дома";
position: absolute;
top: -8px;
left: 12px;
background-color: #bbabb5;
color: #fff;
font-size: 10px;
font-weight: bold;
padding: 3px 7px 4px;
border-radius: 8px;
text-transform: lowercase;
}
.carousel-container {
position: relative;
overflow: hidden;
background: rgb(255 255 255 / 35%);
width: 877px;
}
.carousel-track {
display: flex;
transition: transform 0.4s ease;
}
.house-card {
flex: 0 0 877px;
width: 877px;
padding: 20px;
box-sizing: border-box;
}
.house-header {
display: flex;
justify-content: space-between;
align-items: flex-start;
margin-bottom: 15px;
}
.house-title {
font-size: 20px;
font-weight: 700;
color: #88a3ac;
margin-bottom: 3px;
text-transform: uppercase;
letter-spacing: 0.5px;
border-bottom: 2px solid #88a3ac;
padding-bottom: 5px;
display: inline-block;
}
.house-type {
font-size: 11px;
color: #bbabb5;
font-weight: 500;
text-transform: uppercase;
letter-spacing: 0.3px;
}
.house-price {
background: #88a3ac;
color: #fff;
padding: 8px 12px;
border-radius: 15px;
font-weight: 600;
font-size: 11px;
display: flex;
flex-direction: column;
align-items: center;
gap: 2px;
text-align: center;
min-width: 120px;
}
.house-price-amount {
display: flex;
align-items: center;
gap: 4px;
}
.house-price-type {
font-size: 9px;
opacity: 0.8;
text-transform: uppercase;
letter-spacing: 0.3px;
}
.house-description {
font-size: 13px;
line-height: 1.5;
color: #6f6f6f;
margin-bottom: 15px;
text-align: justify;
}
.house-media-content {
display: flex;
gap: 15px;
margin-bottom: 15px;
}
.house-gif {
width: 130px;
height: 200px;
border-radius: 6px;
overflow: hidden;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
flex-shrink: 0;
}
.house-gif img {
width: 100%;
height: 100%;
object-fit: cover;
}
.house-content {
flex: 1;
display: flex;
flex-direction: column;
}
.house-details {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
margin-bottom: 15px;
}
.house-address {
font-weight: 600;
color: #88a3ac;
margin-bottom: 6px;
font-size: 13px;
}
.detail-section {
background: rgba(255, 255, 255, 0.2);
padding: 10px;
border-left: 2px solid #88a3ac;
}
.detail-section.neighbors {
border-left-color: #bbabb5;
}
.detail-title {
font-weight: 600;
color: #88a3ac;
margin-bottom: 6px;
font-size: 11px;
text-transform: uppercase;
letter-spacing: 0.3px;
display: flex;
align-items: center;
gap: 4px;
}
.detail-title.neighbors-title {
color: #bbabb5;
}
.detail-content {
font-size: 11px;
color: #6f6f6f;
line-height: 1.3;
}
.amenities-list {
display: flex;
flex-wrap: wrap;
gap: 4px;
}
.amenity-item {
background: rgba(136, 163, 172, 0.1);
color: #88a3ac;
padding: 2px 6px;
border-radius: 8px;
font-size: 10px;
font-weight: 500;
}
.neighbors-list {
display: flex;
flex-wrap: wrap;
gap: 4px;
}
.neighbor-item {
background: rgba(187, 171, 181, 0.1);
color: #bbabb5;
padding: 2px 6px;
border-radius: 8px;
font-size: 10px;
font-weight: 500;
}
.apartments-section {
background: rgba(255, 255, 255, 0.2);
padding: 10px;
border-left: 2px solid #88a3ac;
}
.apartments-title {
font-weight: 600;
color: #88a3ac;
margin-bottom: 8px;
font-size: 11px;
text-transform: uppercase;
letter-spacing: 0.3px;
display: flex;
align-items: center;
gap: 4px;
}
.apartments-grid {
display: flex;
flex-direction: column;
gap: 4px;
}
.apartment-item {
background: rgba(255, 255, 255, 0.05);
padding: 6px 8px;
border-radius: 4px;
display: flex;
align-items: center;
gap: 8px;
transition: all 0.2s ease;
}
.apartment-item:hover {
background: rgba(136, 163, 172, 0.1);
transform: translateX(2px);
}
.apartment-number {
font-weight: 600;
color: #88a3ac;
min-width: 60px;
font-size: 10px;
}
.apartment-status {
flex: 1;
font-size: 10px;
}
.apartment-status.free {
color: #49925f;
font-style: italic;
}
.apartment-status.occupied {
color: #6f6f6f;
}
.navigation {
display: flex;
justify-content: center;
align-items: center;
gap: 15px;
margin-top: 15px;
}
.nav-btn {
background: #88a3ac;
color: #fff;
border: none;
width: 30px;
height: 30px;
border-radius: 50%;
cursor: pointer;
font-size: 14px;
font-weight: bold;
transition: all 0.2s ease;
display: flex;
align-items: center;
justify-content: center;
}
.nav-btn:hover:not(:disabled) {
background: #bbabb5;
transform: scale(1.05);
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
}
.nav-btn:disabled {
background: #ccc;
cursor: not-allowed;
opacity: 0.5;
}
.indicators {
display: flex;
gap: 6px;
}
.indicator {
width: 8px;
height: 8px;
border-radius: 50%;
background: rgba(136, 163, 172, 0.3);
cursor: pointer;
transition: all 0.2s ease;
}
.indicator.active {
background: #88a3ac;
transform: scale(1.2);
}
.indicator:hover {
background: #bbabb5;
}
.counter {
color: #6f6f6f;
font-size: 11px;
font-weight: 500;
}
/* Иконки */
.icon {
width: 12px;
height: 12px;
display: inline-block;
}
.icon-home::before {
content: "🏠";
}
.icon-neighbors::before {
content: "👥";
}
.icon-apartments::before {
content: "🏢";
}
.icon-coin {
margin-bottom: 1px;
}
.icon-coin::before {
content: "💰";
}
.icon-amenities::before {
content: "✨";
}
</style>
<body>
<div class="main-container">
<!-- Секция с каруселью -->
<div class="carousel-section">
<div class="carousel-header">
<p style="color: #6f6f6f; margin: 0">Описание темы</p>
</div>
<div class="carousel-container">
<div class="carousel-track" id="carouselTrack">
<!-- Карточки домов будут сгенерированы через JavaScript -->
</div>
</div>
<div class="navigation">
<button class="nav-btn" id="prevBtn">‹</button>
<div class="indicators" id="indicators">
<!-- Индикаторы будут сгенерированы через JavaScript -->
</div>
<button class="nav-btn" id="nextBtn">›</button>
</div>
<div style="text-align: center; margin-top: 10px">
<span class="counter" id="counter">1 / 1</span>
</div>
</div>
</div>
<script>
// Данные о домах
const housesData = [
{
address: "изумрудная аллея, 256",
type: "аренда/продажа",
price: "договорная",
gif: "https://upforme.ru/uploads/001c/85/fe/3/307234.gif",
description:
"трёхэтажный дом на несколько квартир в живописной тампе — редкая находка для ценителей жизни у океана. современное здание с просторными балконами и панорамными окнами открывает потрясающий вид на воду и закаты над заливом. каждая квартира продумана до мелочей: светлые интерьеры, функциональные планировки и стильная отделка. на территории — частная парковка, зелёная зона для отдыха и прямой выход к пляжу. идеальное место для жизни, отдыха или инвестиций в сердце флориды.",
amenities: ["одна спальня", "одна ванная", "гостиная", "кухня", "кладовая", "без лифта"],
neighbors: ["солнечная аллея, 12", "океанский бульвар, 89"],
apartments: [
{ number: "квартира 1", status: "free", residents: null },
{ number: "квартира 2", status: "occupied", residents: "Ande Barckett & Lionell Stewens" },
{ number: "квартира 3", status: "free", residents: null }
]
},
{
address: "солнечная аллея, 12",
type: "только аренда",
price: "$850/месяц",
gif: "https://upforme.ru/uploads/001c/85/fe/3/307234.gif",
description:
"уютный двухэтажный коттедж в тихом районе тампы с собственным садом и террасой. дом полностью меблирован и готов к заселению. просторная гостиная с камином, современная кухня с островом и панорамными окнами, выходящими в сад. на втором этаже две спальни с собственными ванными комнатами. идеально подходит для семьи или пары, ценящей комфорт и уединение.",
amenities: [
"две спальни",
"две ванные",
"гостиная с камином",
"кухня с островом",
"терраса",
"сад",
"парковка"
],
neighbors: ["изумрудная аллея, 256", "цветочная улица, 45"],
apartments: [{ number: "основной дом", status: "occupied", residents: "Sarah & Michael Thompson" }]
},
{
address: "океанский бульвар, 89",
type: "продажа",
price: "$1,200,000",
gif: "https://upforme.ru/uploads/001c/85/fe/3/307234.gif",
description:
"роскошный пентхаус на последнем этаже с панорамным видом на океан. эксклюзивная недвижимость с собственным лифтом, просторными террасами и бассейном на крыше. интерьер выполнен в современном стиле с использованием натуральных материалов. три спальни, четыре ванные комнаты, кабинет, винная комната и гардеробная. консьерж-сервис и охрана 24/7.",
amenities: [
"три спальни",
"четыре ванные",
"кабинет",
"винная комната",
"бассейн на крыше",
"консьерж",
"охрана 24/7"
],
neighbors: ["изумрудная аллея, 256", "мраморная улица, 1"],
apartments: [{ number: "пентхаус", status: "free", residents: null }]
},
{
address: "цветочная улица, 45",
type: "аренда/продажа",
price: "$650/месяц или $450,000",
gif: "https://upforme.ru/uploads/001c/85/fe/3/307234.gif",
description:
"стильная студия в историческом центре города с высокими потолками и оригинальными кирпичными стенами. недавно отремонтированная квартира сочетает в себе винтажный шарм и современные удобства. большие окна обеспечивают отличное естественное освещение. в шаговой доступности кафе, галереи и бутики. идеально подходит для молодого профессионала или студента.",
amenities: ["студия", "высокие потолки", "кирпичные стены", "винтажный стиль", "центр города"],
neighbors: ["солнечная аллея, 12", "артистическая улица, 7"],
apartments: [{ number: "студия", status: "free", residents: null }]
}
];
let currentSlide = 0;
// Генерация карточек домов
function generateHouseCards() {
const track = document.getElementById("carouselTrack");
track.innerHTML = "";
housesData.forEach((house, index) => {
const card = document.createElement("div");
card.className = "house-card";
card.innerHTML = `
<div class="house-header">
<div>
<h2 class="house-title">${house.address}</h2>
</div>
<div class="house-price">
<div class="house-price-amount">
<span class="icon icon-coin"></span>
${house.price}
</div>
<div class="house-price-type">${house.type}</div>
</div>
</div>
<div class="house-media-content">
<div class="house-gif">
<img src="${house.gif}" alt="${house.address}">
</div>
<div class="house-content">
<div class="house-description">
${house.description}
</div>
</div>
</div>
<div class="house-details">
<div class="detail-section">
<div class="detail-title">
<span class="icon icon-amenities"></span>
удобства
</div>
<div class="detail-content">
<div class="amenities-list">
${house.amenities.map((amenity) => `<span class="amenity-item">${amenity}</span>`).join("")}
</div>
</div>
</div>
<div class="detail-section neighbors">
<div class="detail-title neighbors-title">
<span class="icon icon-neighbors"></span>
соседи
</div>
<div class="detail-content">
<div class="neighbors-list">
${house.neighbors.map((neighbor) => `<span class="neighbor-item">${neighbor}</span>`).join("")}
</div>
</div>
</div>
</div>
<div class="apartments-section">
<div class="apartments-title">
<span class="icon icon-apartments"></span>
квартиры
</div>
<div class="apartments-grid">
${house.apartments
.map(
(apt) => `
<div class="apartment-item">
<div class="apartment-number">♦ ${apt.number}</div>
<div class="apartment-status ${apt.status}">
${apt.status === "free" ? "свободно" : apt.residents}
</div>
</div>
`
)
.join("")}
</div>
</div>
`;
track.appendChild(card);
});
}
// Генерация индикаторов
function generateIndicators() {
const indicatorsContainer = document.getElementById("indicators");
indicatorsContainer.innerHTML = "";
housesData.forEach((_, index) => {
const indicator = document.createElement("div");
indicator.className = "indicator";
if (index === 0) indicator.classList.add("active");
indicator.addEventListener("click", () => goToSlide(index));
indicatorsContainer.appendChild(indicator);
});
}
// Переход к слайду
function goToSlide(slideIndex) {
const track = document.getElementById("carouselTrack");
const indicators = document.querySelectorAll(".indicator");
const counter = document.getElementById("counter");
const prevBtn = document.getElementById("prevBtn");
const nextBtn = document.getElementById("nextBtn");
currentSlide = slideIndex;
// Используем точное позиционирование в пикселях
track.style.transform = `translateX(-${currentSlide * 877}px)`;
// Обновляем индикаторы
indicators.forEach((indicator, index) => {
indicator.classList.toggle("active", index === currentSlide);
});
// Обновляем счетчик
counter.textContent = `${currentSlide + 1} / ${housesData.length}`;
// Обновляем кнопки навигации
prevBtn.disabled = currentSlide === 0;
nextBtn.disabled = currentSlide === housesData.length - 1;
}
// Следующий слайд
function nextSlide() {
if (currentSlide < housesData.length - 1) {
goToSlide(currentSlide + 1);
}
}
// Предыдущий слайд
function prevSlide() {
if (currentSlide > 0) {
goToSlide(currentSlide - 1);
}
}
// Инициализация
// document.addEventListener('DOMContentLoaded', function() {
setTimeout(() => {
generateHouseCards();
generateIndicators();
goToSlide(0);
// Обработчики событий
document.getElementById("nextBtn").addEventListener("click", nextSlide);
document.getElementById("prevBtn").addEventListener("click", prevSlide);
// Поддержка клавиатуры
document.addEventListener("keydown", function (e) {
if (e.key === "ArrowLeft") {
prevSlide();
} else if (e.key === "ArrowRight") {
nextSlide();
}
});
}, 1000);
</script>
[hideprofile]
</body>
Страница: 1