..
елка
Сообщений 1 страница 9 из 9
Поделиться22025-11-13 21:10:48
[html]<!-- ====================== Ёлка с поздравлениями ====================== -->
<div id="christmas-container">
<div id="tree-wrapper"></div>
<div id="gift-form">
<input type="text" id="username" placeholder="Ваш ник">
<textarea id="message" rows="3" placeholder="Ваше поздравление"></textarea>
<select id="icon-select">
<option value="https://forumstatic.ru/files/001a/fc/23/70482.png">Подарок 1</option>
<option value="https://forumstatic.ru/files/001a/fc/23/70483.png">Подарок 2</option>
<option value="https://forumstatic.ru/files/001a/fc/23/70484.png">Подарок 3</option>
</select>
<button id="send-gift" title="Отправить подарок"></button>
</div>
</div>
<!-- ====================== Стили ====================== -->
<style>
#christmas-container {
display: flex;
justify-content: flex-start; /* Ёлка слева, форма справа */
align-items: flex-start;
gap: 20px;
flex-wrap: wrap; /* На маленьких экранах форма под ёлкой */
margin-top: 20px;
position: relative;
z-index: 1;
}
#tree-wrapper {
position: relative;
width: 600px;
height: 800px;
background: url("https://forumstatic.ru/files/0013/65/ed/19383.jpg") no-repeat center top;
background-size: contain;
z-index: 1; /* Ёлка на нижнем уровне */
}
#gift-form {
width: 300px;
background: rgba(255,255,255,0.95);
padding: 10px 15px;
border-radius: 10px;
box-shadow: 0 0 6px rgba(0,0,0,0.2);
display: flex;
flex-direction: column;
gap: 5px;
z-index: 2; /* Форма выше ёлки */
}
#gift-form input, #gift-form textarea, #gift-form select {
width: 100%;
padding: 6px 8px;
border-radius: 6px;
border: 1px solid #aaa;
font-size: 13px;
}
#gift-form button {
width: 40px;
height: 40px;
margin-top: 5px;
border: none;
cursor: pointer;
background: url(https://forumstatic.ru/files/001a/fc/23/70482.png) no-repeat center;
background-size: 28px;
}
.gift {
position: absolute;
width: 32px;
height: 32px;
cursor: pointer;
transition: transform 0.2s;
z-index: 50;
}
.gift:hover { transform: scale(1.3); z-index: 150; }
.gift-note {
display: none;
position: absolute;
top: -40px;
left: 50%;
transform: translateX(-50%);
background: rgba(255,255,255,0.95);
border-radius: 6px;
padding: 6px 10px;
font-size: 12px;
white-space: nowrap;
box-shadow: 0 2px 4px rgba(0,0,0,0.2);
}
.gift:hover .gift-note { display: block; }
</style>
<!-- ====================== Скрипты RusFF ====================== -->
<script>
var temaID = 1514; // <-- сюда вставьте ID вашей темы
</script>
<script type="text/javascript" src="https://forumstatic.ru/files/0014/cc/0a/58042.js"></script>
<script type="text/javascript" src="https://forumstatic.ru/files/0014/cc/0a/54653.js"></script>
<script type="text/javascript" src="https://forumstatic.ru/files/0013/65/ed/76531.js"></script>
<!-- ====================== JS логика подарков ====================== -->
<script>
const tree = document.getElementById('tree-wrapper');
const sendButton = document.getElementById('send-gift');
// Загрузка подарков из темы
async function loadGifts() {
if (typeof Christmas_Tree.getGifts !== 'function') return;
const gifts = await Christmas_Tree.getGifts();
tree.innerHTML = '';
gifts.forEach(g => {
const el = document.createElement('div');
el.className = 'gift';
el.style.left = g.x + 'px';
el.style.top = g.y + 'px';
el.innerHTML = `
<img src="${g.icon}" width="32" height="32">
<div class="gift-note">🎁 ${g.user}: ${g.msg}</div>
`;
tree.appendChild(el);
});
}
// Рандомная позиция подарка
function getRandomPosition() {
return {
x: Math.random() * (tree.clientWidth - 32),
y: Math.random() * (tree.clientHeight - 32)
};
}
// Отправка подарка
sendButton.addEventListener('click', async () => {
const name = document.getElementById('username').value.trim();
const msg = document.getElementById('message').value.trim();
const icon = document.getElementById('icon-select').value;
if (!name || !msg) return alert('Введите ник и поздравление!');
const pos = getRandomPosition();
if (typeof Christmas_Tree.sendGift === 'function') {
await Christmas_Tree.sendGift(name, msg, icon, pos.x, pos.y);
document.getElementById('message').value = '';
loadGifts();
} else {
alert('Скрипт ёлки не подключен!');
}
});
// Первичная загрузка при открытии темы
loadGifts();
</script>[/html]
Поделиться32025-11-13 21:20:29
[html]<!-- Подключение MyBB SDK -->
<script src="https://cdn.jsdelivr.net/npm/@quadrosystems/mybb-sdk@0.9.7/lib/index.min.js"></script>
<div style="display:flex; gap:20px;">
<!-- Левая часть: Елка -->
<div id="tree-container" style="position:relative; width:400px; height:600px; background:url('https://i.imgur.com/your_tree_image.png') no-repeat center/contain;">
<!-- Подарки будут добавляться сюда -->
</div>
<!-- Правая часть: Форма поздравления -->
<div style="flex:1; display:flex; flex-direction:column; gap:10px;">
<textarea id="message" placeholder="Ваше поздравление" rows="5" style="width:100%;"></textarea>
<div>
<span>Выберите подарок:</span><br>
<img src="https://i.imgur.com/gift1.png" class="gift-option" data-gift="gift1" style="width:50px; cursor:pointer; border:2px solid transparent; margin:5px;">
<img src="https://i.imgur.com/gift2.png" class="gift-option" data-gift="gift2" style="width:50px; cursor:pointer; border:2px solid transparent; margin:5px;">
<img src="https://i.imgur.com/gift3.png" class="gift-option" data-gift="gift3" style="width:50px; cursor:pointer; border:2px solid transparent; margin:5px;">
</div>
<button id="send-btn">Отправить</button>
</div>
</div>
<script>
const sdk = new MyBBSDK({
apiKey: '$2a$10$ybd0vsRA5QqwRhby6GrjduwTLCwduPP9o3Baa8fvq.oJBZi4Gi172',
forumUrl: 'https://test006.rusff.me', // URL вашего форума
threadId: 16, // ID темы, где отображаем сообщение
});
let selectedGift = null;
// Выбор подарка
document.querySelectorAll('.gift-option').forEach(img => {
img.addEventListener('click', () => {
document.querySelectorAll('.gift-option').forEach(i => i.style.border='2px solid transparent');
img.style.border = '2px solid green';
selectedGift = img.dataset.gift;
});
});
// Отправка поздравления
document.getElementById('send-btn').addEventListener('click', async () => {
const message = document.getElementById('message').value.trim();
if(!message || !selectedGift) {
alert('Введите поздравление и выберите подарок');
return;
}
// Добавляем подарок на елку локально
const tree = document.getElementById('tree-container');
const giftImg = document.createElement('img');
giftImg.src = `https://i.imgur.com/${selectedGift}.png`;
giftImg.style.position = 'absolute';
giftImg.style.width = '50px';
giftImg.style.left = Math.random() * (tree.clientWidth - 50) + 'px';
giftImg.style.top = Math.random() * (tree.clientHeight - 50) + 'px';
tree.appendChild(giftImg);
// Сохраняем данные через API (в одном сообщении темы)
const data = {
message,
gift: selectedGift,
timestamp: Date.now()
};
try {
// Берем текущее сообщение, добавляем новое поздравление
const threadMessages = await sdk.getThreadMessages(123);
let mainMessage = threadMessages[0]; // предположим, что основное сообщение - первое
let content = JSON.parse(mainMessage.content || '[]');
content.push(data);
await sdk.editPost(mainMessage.pid, JSON.stringify(content));
document.getElementById('message').value = '';
selectedGift = null;
document.querySelectorAll('.gift-option').forEach(i => i.style.border='2px solid transparent');
} catch(e) {
console.error(e);
alert('Ошибка при отправке');
}
});
// При загрузке страницы отображаем все подарки
(async function loadExisting() {
try {
const threadMessages = await sdk.getThreadMessages(123);
let mainMessage = threadMessages[0];
const content = JSON.parse(mainMessage.content || '[]');
const tree = document.getElementById('tree-container');
content.forEach(data => {
const giftImg = document.createElement('img');
giftImg.src = `https://i.imgur.com/${data.gift}.png`;
giftImg.style.position = 'absolute';
giftImg.style.width = '50px';
giftImg.style.left = Math.random() * (tree.clientWidth - 50) + 'px';
giftImg.style.top = Math.random() * (tree.clientHeight - 50) + 'px';
tree.appendChild(giftImg);
});
} catch(e) {
console.error(e);
}
})();
</script>[/html]
Поделиться42025-11-13 21:39:04
[html]<style>
/* Стили для оформления */
.christmas-container {
display: flex;
gap: 20px;
max-width: 800px;
margin: 0 auto;
border: 1px solid #ccc;
padding: 20px;
background-color: #f9f9f9;
font-family: Arial, sans-serif;
}
.tree-area {
flex: 1;
position: relative;
text-align: center;
}
.form-area {
flex: 1;
padding: 10px;
background-color: #e8f5e9;
border-radius: 8px;
}
#christmasTree {
width: 100%;
max-width: 300px;
height: auto;
}
.gift-icon {
position: absolute;
width: 30px; /* Размер иконки подарка */
height: 30px;
background-size: contain;
background-repeat: no-repeat;
cursor: pointer;
/* Условные позиции, будут изменены JS */
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
transition: opacity 0.3s;
}
/* Стили для иконок подарков (вам нужно будет загрузить эти изображения) */
.gift1 { background-image: url('URL_ИКОНКИ_ПОДАРКА_1.png'); }
.gift2 { background-image: url('URL_ИКОНКИ_ПОДАРКА_2.png'); }
.gift3 { background-image: url('URL_ИКОНКИ_ПОДАРКА_3.png'); }
.gift-icon:hover { opacity: 0.7; }
.message-tooltip {
position: absolute;
background: #333;
color: white;
padding: 5px 10px;
border-radius: 5px;
z-index: 10;
white-space: nowrap;
pointer-events: none; /* Чтобы не мешать клику */
opacity: 0;
transition: opacity 0.2s;
transform: translate(15px, -100%);
}
.gift-icon:hover .message-tooltip {
opacity: 1;
}
</style>
<div class="christmas-container">
<div class="tree-area">
<h2>🎄 Наше Рождественское Дерево</h2>
<img id="christmasTree" src="URL_ВАШЕГО_ИЗОБРАЖЕНИЯ_ЕЛКИ.png" alt="Елка">
<div id="giftsContainer">
</div>
</div>
<div class="form-area">
<h2>💌 Отправить Поздравление</h2>
<form id="giftForm">
<p>
<label for="userName">Ваше имя:</label>
<input type="text" id="userName" required style="width: 90%;">
</p>
<p>
<label for="userMessage">Поздравление:</label>
<textarea id="userMessage" required maxlength="150" style="width: 90%; height: 60px;"></textarea>
</p>
<p>
<strong>Выберите Подарок:</strong><br>
<label><input type="radio" name="giftType" value="gift1" required> </label><br>
<label><input type="radio" name="giftType" value="gift2"> </label><br>
<label><input type="radio" name="giftType" value="gift3"> </label>
</p>
<button type="submit">Повесить Подарок!</button>
<p id="formStatus" style="color: red; font-weight: bold;"></p>
</form>
</div>
</div>
<script>
// ⚠️ ВАЖНО: Замените это на фактический путь к вашему JSON-файлу
const JSON_URL = 'https://github.com/desp180/gifts.json.git';
// Координаты для размещения подарков на елке (нормализованные 0-100)
// Добавьте больше, чтобы подарки не перекрывались
const GIFT_POSITIONS = [
{ top: 15, left: 50 },
{ top: 30, left: 35 },
{ top: 30, left: 65 },
{ top: 45, left: 25 },
{ top: 45, left: 75 },
{ top: 60, left: 50 },
{ top: 75, left: 30 },
{ top: 75, left: 70 }
// Добавьте еще
];
/**
* Отображает подарки из данных JSON на елке
* @param {Array} gifts - Массив объектов подарков
*/
function renderGifts(gifts) {
const container = document.getElementById('giftsContainer');
container.innerHTML = ''; // Очистка предыдущих подарков
gifts.forEach((giftData, index) => {
if (index >= GIFT_POSITIONS.length) return; // Не размещать больше, чем есть позиций
const pos = GIFT_POSITIONS[index];
const giftDiv = document.createElement('div');
giftDiv.className = `gift-icon ${giftData.gift}`;
giftDiv.style.top = `${pos.top}%`;
giftDiv.style.left = `${pos.left}%`;
// Всплывающая подсказка с сообщением
const tooltip = document.createElement('div');
tooltip.className = 'message-tooltip';
tooltip.innerHTML = `<strong>${giftData.user}</strong>: ${giftData.message}`;
giftDiv.appendChild(tooltip);
// Обработчик для отображения подсказки
giftDiv.onmouseover = () => tooltip.style.opacity = 1;
giftDiv.onmouseout = () => tooltip.style.opacity = 0;
container.appendChild(giftDiv);
});
}
/**
* Загружает и отображает данные из JSON
*/
function fetchAndRenderGifts() {
fetch(JSON_URL + '?' + new Date().getTime()) // Добавляем timestamp для обхода кэша
.then(response => {
if (!response.ok) throw new Error('Ошибка сети или JSON-файл не найден');
return response.json();
})
.then(data => {
renderGifts(data);
document.getElementById('formStatus').textContent = 'Подарки успешно загружены.';
})
.catch(error => {
console.error('Ошибка загрузки JSON:', error);
document.getElementById('formStatus').textContent = 'Не удалось загрузить подарки. Проверьте путь к JSON.';
});
}
// Обработчик отправки формы (СИМУЛЯЦИЯ)
document.getElementById('giftForm').addEventListener('submit', function(e) {
e.preventDefault();
const userName = document.getElementById('userName').value.trim();
const userMessage = document.getElementById('userMessage').value.trim();
const giftType = document.querySelector('input[name="giftType"]:checked').value;
const statusElement = document.getElementById('formStatus');
if (userName === "" || userMessage === "" || !giftType) {
statusElement.textContent = 'Заполните все поля!';
return;
}
// --- ⚠️ СИМУЛЯЦИЯ ОТПРАВКИ ---
// В РЕАЛЬНОСТИ ЗДЕСЬ НУЖЕН AJAX-ЗАПРОС К ВАШЕМУ СЕРВЕРНОМУ СКРИПТУ
// (например, PHP), который обновит файл gifts.json.
// Браузерный JavaScript НЕ МОЖЕТ напрямую редактировать файлы на сервере.
statusElement.textContent = 'Отправка... (В реальном приложении здесь нужен серверный скрипт для сохранения данных)';
const newGift = {
user: userName,
gift: giftType,
message: userMessage
};
// В рамках симуляции: просто отображаем, что "подарок отправлен"
setTimeout(() => {
statusElement.textContent = 'Поздравление "отправлено" и будет видно после обновления JSON-файла.';
// Очистка формы
document.getElementById('giftForm').reset();
// Для отображения изменений на клиенте без перезагрузки:
// Попробуем снова загрузить (для этого вам нужно вручную обновить gifts.json)
fetchAndRenderGifts();
}, 1500);
});
// Первоначальная загрузка подарков при загрузке страницы
fetchAndRenderGifts();
// Регулярное обновление (чтобы видеть подарки других игроков)
// Установите интервал, например, раз в 30 секунд
setInterval(fetchAndRenderGifts, 30000);
</script>[/html]
Поделиться52025-11-13 22:46:23
[html]<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>Елка с подарками</title>
<style>
body {
font-family: sans-serif;
display: flex;
gap: 20px;
}
#tree-container {
position: relative;
width: 400px;
height: 600px;
background: url('https://i.imgur.com/your_tree_image.png') no-repeat center/contain;
border: 2px solid #ccc;
border-radius: 10px;
}
.gift-option {
width: 50px;
cursor: pointer;
border: 2px solid transparent;
margin: 5px;
}
.gift-option.selected {
border-color: green;
}
#message {
width: 100%;
resize: none;
}
</style>
</head>
<body>
<!-- Елка -->
<div id="tree-container"></div>
<!-- Форма -->
<div style="flex:1; display:flex; flex-direction:column; gap:10px;">
<textarea id="message" placeholder="Ваше поздравление" rows="4"></textarea>
<div>
<span>Выберите подарок:</span><br>
<img src="https://i.imgur.com/gift1.png" class="gift-option" data-gift="gift1">
<img src="https://i.imgur.com/gift2.png" class="gift-option" data-gift="gift2">
<img src="https://i.imgur.com/gift3.png" class="gift-option" data-gift="gift3">
</div>
<button id="send-btn">Отправить</button>
</div>
<script>
const JSON_URL = "gifts.json"; // файл на сервере
let selectedGift = null;
// Выбор подарка
document.querySelectorAll('.gift-option').forEach(img => {
img.addEventListener('click', () => {
document.querySelectorAll('.gift-option').forEach(i => i.classList.remove('selected'));
img.classList.add('selected');
selectedGift = img.dataset.gift;
});
});
// Добавление подарка на елку
function addGiftToTree(gift, x, y) {
const tree = document.getElementById('tree-container');
const img = document.createElement('img');
img.src = `https://i.imgur.com/${gift}.png`;
img.style.position = 'absolute';
img.style.width = '50px';
img.style.left = (x || Math.random() * (tree.clientWidth - 50)) + 'px';
img.style.top = (y || Math.random() * (tree.clientHeight - 50)) + 'px';
tree.appendChild(img);
}
// Загрузка JSON с сервера
async function fetchAndRenderGifts() {
try {
const response = await fetch(JSON_URL + '?t=' + Date.now());
const data = await response.json();
const tree = document.getElementById('tree-container');
tree.innerHTML = ''; // очищаем старые подарки
data.forEach(item => addGiftToTree(item.gift, item.x, item.y));
} catch (e) {
console.error("Ошибка загрузки JSON:", e);
}
}
// Отправка поздравления
document.getElementById('send-btn').addEventListener('click', async () => {
const message = document.getElementById('message').value.trim();
if (!message || !selectedGift) {
alert('Введите поздравление и выберите подарок');
return;
}
const giftData = {
message,
gift: selectedGift,
x: Math.random() * 350,
y: Math.random() * 500,
time: Date.now()
};
try {
// Получаем текущий JSON
const res = await fetch(JSON_URL + '?t=' + Date.now());
let data = [];
if (res.ok) data = await res.json();
data.push(giftData);
// Отправляем обновлённый JSON на сервер
await fetch(JSON_URL, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(data)
});
document.getElementById('message').value = '';
document.querySelectorAll('.gift-option').forEach(i => i.classList.remove('selected'));
selectedGift = null;
fetchAndRenderGifts(); // обновляем сразу
} catch (e) {
console.error("Ошибка сохранения JSON:", e);
}
});
// Автообновление каждые 5 секунд
setInterval(fetchAndRenderGifts, 5000);
fetchAndRenderGifts();
</script>
</body>
</html>[/html]
Поделиться62025-11-13 22:46:49
[html]<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>Ёлка с пожеланиями</title>
<style>
body {
background: #0b1d2a;
color: white;
font-family: sans-serif;
display: flex;
justify-content: center;
gap: 20px;
margin-top: 20px;
}
#tree {
position: relative;
}
#tree img {
width: 400px;
}
.gift {
position: absolute;
width: 40px;
transition: transform 0.3s ease;
}
.gift:hover {
transform: scale(1.2);
}
form {
display: flex;
flex-direction: column;
gap: 10px;
}
.gifts {
display: flex;
gap: 10px;
}
.gifts img {
width: 40px;
cursor: pointer;
border: 2px solid transparent;
border-radius: 6px;
}
.gifts img.selected {
border-color: gold;
}
</style>
</head>
<body>
<div id="tree">
<img src="https://i.imgur.com/kX8iD8F.png" alt="Ёлка">
</div>
<form id="giftForm">
<input type="text" id="name" placeholder="Ваше имя" required>
<textarea id="message" placeholder="Ваше поздравление" required></textarea>
<div class="gifts">
<img src="https://i.imgur.com/Uq2ZbK3.png" data-gift="gift1">
<img src="https://i.imgur.com/6z5HZSp.png" data-gift="gift2">
<img src="https://i.imgur.com/gx7Z9Qq.png" data-gift="gift3">
</div>
<button type="submit">Отправить подарок</button>
</form>
<script>
const gifts = document.querySelectorAll('.gifts img');
let selectedGift = null;
gifts.forEach(g => g.addEventListener('click', () => {
gifts.forEach(img => img.classList.remove('selected'));
g.classList.add('selected');
selectedGift = g.dataset.gift;
}));
const tree = document.getElementById('tree');
const form = document.getElementById('giftForm');
const apiUrl = 'save_gifts.php';
form.addEventListener('submit', async (e) => {
e.preventDefault();
const name = document.getElementById('name').value.trim();
const message = document.getElementById('message').value.trim();
if (!selectedGift) return alert('Выберите подарок!');
const response = await fetch(apiUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name, message, gift: selectedGift })
});
const data = await response.json();
if (data.status === 'ok') {
alert('Подарок добавлен!');
renderGifts();
form.reset();
gifts.forEach(g => g.classList.remove('selected'));
selectedGift = null;
} else {
alert('Ошибка при добавлении подарка');
}
});
async function renderGifts() {
const res = await fetch(apiUrl);
const all = await res.json();
tree.querySelectorAll('.gift').forEach(el => el.remove());
all.forEach((item, i) => {
const img = document.createElement('img');
img.src = document.querySelector(`[data-gift="${item.gift}"]`).src;
img.className = 'gift';
img.style.left = (50 + Math.random() * 300) + 'px';
img.style.top = (100 + Math.random() * 300) + 'px';
img.title = `${item.name}: ${item.message}`;
tree.appendChild(img);
});
}
renderGifts();
</script>
</body>
</html>[/html]
Поделиться72025-11-13 23:15:06
[html]
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="utf-8">
<title>Ёлка с пожеланиями (jsonbin.io)</title>
<style>
body { background:#0b1d2a; color:#fff; font-family:sans-serif; display:flex; justify-content:center; gap:20px; margin-top:20px; }
#tree { position:relative; width:420px; height:620px; }
#tree img.tree-img { width:100%; height:auto; display:block; }
.gift { position:absolute; width:44px; transition:transform .2s; }
.gift:hover { transform:scale(1.15); }
form { width:360px; display:flex; flex-direction:column; gap:10px; }
.gifts { display:flex; gap:10px; }
.gifts img { width:44px; cursor:pointer; border:2px solid transparent; border-radius:6px; }
.gifts img.selected { border-color:gold; }
textarea, input[type="text"] { width:100%; padding:8px; border-radius:4px; border:1px solid #ccc; }
button { padding:10px; border-radius:6px; background:gold; border:none; cursor:pointer; font-weight:bold; }
.small-note { font-size:12px; color:#ddd; }
</style>
</head>
<body>
<div id="tree">
<img class="tree-img" src="https://i.imgur.com/kX8iD8F.png" alt="Ёлка">
<!-- Подарки будут добавляться сюда -->
</div>
<form id="giftForm">
<input id="name" type="text" placeholder="Ваше имя" required>
<textarea id="message" rows="4" placeholder="Ваше поздравление" required></textarea>
<div class="gifts">
<img src="https://i.imgur.com/Uq2ZbK3.png" data-gift="gift1">
<img src="https://i.imgur.com/6z5HZSp.png" data-gift="gift2">
<img src="https://i.imgur.com/gx7Z9Qq.png" data-gift="gift3">
</div>
<div style="display:flex; gap:10px; align-items:center;">
<button type="submit">Отправить подарок</button>
<div class="small-note">Данные сохраняются в jsonbin.io</div>
</div>
</form>
<script>
/* === НАСТРОЙКИ: ВСТАВЬ СВОИ ЗНАЧЕНИЯ === */
const BIN_ID = "69163b3dd0ea881f40e6bafc"; // <- сюда BIN ID
const MASTER_KEY = "$2a$10$lgEuQI8uB1Q9jbhkh8lMt.hm/w/fNOJQwhicQdi5Fi1RGkweW7L6O"; // <- сюда Master Key (секрет!)
const API_BASE = "https://api.jsonbin.io/v3/b/" + BIN_ID;
/* ======================================= */
const giftsEls = document.querySelectorAll('.gifts img');
let selectedGift = null;
giftsEls.forEach(el => el.addEventListener('click', () => {
giftsEls.forEach(i => i.classList.remove('selected'));
el.classList.add('selected');
selectedGift = el.dataset.gift;
}));
const tree = document.getElementById('tree');
const form = document.getElementById('giftForm');
form.addEventListener('submit', async (e) => {
e.preventDefault();
const name = document.getElementById('name').value.trim();
const message = document.getElementById('message').value.trim();
if (!selectedGift) return alert('Выберите подарок');
// загрузить текущие данные
let current = await loadAllGifts();
if (!Array.isArray(current)) current = [];
// позиция подарка (фиксируем в пределах ёлки)
const x = 30 + Math.random() * (tree.clientWidth - 80);
const y = 80 + Math.random() * (tree.clientHeight - 160);
const newItem = {
name,
message,
gift: selectedGift,
x: Math.round(x),
y: Math.round(y),
time: new Date().toISOString()
};
current.push(newItem);
// сохранить (замена всего контента)
const ok = await saveAllGifts(current);
if (ok) {
alert('Подарок добавлен!');
form.reset();
giftsEls.forEach(i=>i.classList.remove('selected'));
selectedGift = null;
renderGifts(current);
} else {
alert('Ошибка сохранения. Проверьте ключ и BIN ID.');
}
});
async function loadAllGifts() {
try {
const res = await fetch(API_BASE, {
method: 'GET',
headers: {
'X-Master-Key': MASTER_KEY,
'Content-Type': 'application/json'
}
});
if (!res.ok) {
console.error('Ошибка fetch:', res.status, res.statusText);
return [];
}
const json = await res.json();
// json.record содержит массив, если bin создан как array
return json.record || [];
} catch (e) {
console.error('Ошибка загрузки из jsonbin:', e);
return [];
}
}
async function saveAllGifts(dataArray) {
try {
const res = await fetch(API_BASE, {
method: 'PUT',
headers: {
'X-Master-Key': MASTER_KEY,
'Content-Type': 'application/json'
},
body: JSON.stringify({ record: dataArray })
});
if (!res.ok) {
console.error('Ошибка сохранения:', res.status, res.statusText);
return false;
}
return true;
} catch (e) {
console.error('Ошибка при сохранении на jsonbin:', e);
return false;
}
}
function renderGifts(list) {
// очистить старые
tree.querySelectorAll('.gift').forEach(el => el.remove());
(list || []).forEach(item => {
const src = document.querySelector(`[data-gift="${item.gift}"]`).src;
const img = document.createElement('img');
img.src = src;
img.className = 'gift';
img.style.left = (item.x || (30 + Math.random() * 300)) + 'px';
img.style.top = (item.y || (80 + Math.random() * 300)) + 'px';
img.title = `${item.name}: ${item.message}`;
tree.appendChild(img);
});
}
// начальная загрузка и отображение
(async function init() {
const list = await loadAllGifts();
renderGifts(list);
// автообновление каждые 6 секунд, чтобы другие игроки видели изменения
setInterval(async () => {
const fresh = await loadAllGifts();
renderGifts(fresh);
}, 6000);
})();
</script>
</body>
</html>
[/html]
Поделиться82025-11-13 23:23:25
[html]
<div style="display:flex; gap:20px;">
<div id="tree" style="position:relative; width:400px; height:600px;">
<img class="tree-img" src="https://i.imgur.com/kX8iD8F.png" style="width:100%;" alt="Ёлка">
</div>
<form id="giftForm" style="display:flex; flex-direction:column; gap:10px; width:300px;">
<input id="name" type="text" placeholder="Ваше имя" required>
<textarea id="message" rows="4" placeholder="Поздравление" required></textarea>
<div class="gifts" style="display:flex; gap:10px;">
<img src="https://i.imgur.com/Uq2ZbK3.png" data-gift="gift1" style="width:44px;cursor:pointer;border:2px solid transparent;border-radius:6px;">
<img src="https://i.imgur.com/6z5HZSp.png" data-gift="gift2" style="width:44px;cursor:pointer;border:2px solid transparent;border-radius:6px;">
<img src="https://i.imgur.com/gx7Z9Qq.png" data-gift="gift3" style="width:44px;cursor:pointer;border:2px solid transparent;border-radius:6px;">
</div>
<button type="submit" style="padding:10px;border:none;border-radius:6px;background:gold;cursor:pointer;font-weight:bold;">Отправить подарок</button>
</form>
</div>
<script>
const giftsEls = document.querySelectorAll('.gifts img');
let selectedGift = null;
giftsEls.forEach(el => el.addEventListener('click', () => {
giftsEls.forEach(i => i.style.borderColor = 'transparent');
el.style.borderColor = 'gold';
selectedGift = el.dataset.gift;
}));
const tree = document.getElementById('tree');
const form = document.getElementById('giftForm');
const apiUrl = "proxy.php"; // теперь через proxy
form.addEventListener('submit', async e => {
e.preventDefault();
const name = document.getElementById('name').value.trim();
const message = document.getElementById('message').value.trim();
if (!selectedGift) return alert('Выберите подарок!');
const response = await fetch(apiUrl, {
method:'POST',
headers:{'Content-Type':'application/json'},
body: JSON.stringify({name,message,gift:selectedGift})
});
const data = await response.json();
if(data.status==='ok'){
form.reset();
giftsEls.forEach(i=>i.style.borderColor='transparent');
selectedGift = null;
renderGifts(await fetchGifts());
} else {
alert('Ошибка при добавлении подарка');
}
});
async function fetchGifts(){
const res = await fetch(apiUrl);
const json = await res.json();
return json.record || [];
}
function renderGifts(list){
tree.querySelectorAll('.gift').forEach(el=>el.remove());
list.forEach(item=>{
if(item.system) return; // игнорируем заглушку
const src = document.querySelector(`[data-gift="${item.gift}"]`)?.src || '';
if(!src) return;
const img = document.createElement('img');
img.src = src;
img.className = 'gift';
img.style.position='absolute';
img.style.left=(item.x||30)+'px';
img.style.top=(item.y||80)+'px';
img.title = `${item.name}: ${item.message}`;
img.style.width='44px';
tree.appendChild(img);
});
}
// начальная загрузка и автообновление каждые 6 секунд
(async function init(){
renderGifts(await fetchGifts());
setInterval(async()=>renderGifts(await fetchGifts()),6000);
})();
</script>
[/html]
Поделиться92025-11-15 21:45:51
[html]<button id="find-nick-in-html-btn" type="button"
style="padding: 10px 20px; margin-top: 15px; background-color: #ff9800; color: white; border: none; border-radius: 5px; cursor: pointer; font-weight: bold;">
Поиск Ника в HTML-коде
</button>
<script>
document.addEventListener('DOMContentLoaded', function() {
const checkButton = document.getElementById('find-nick-in-html-btn');
checkButton.addEventListener('click', function() {
let foundNick = null;
// 1. Поиск по распространенному классу (например, для приветствия)
// Замените '.user-nick-class' на реальный класс, если знаете его
const nickElement = document.querySelector('.user-nick-class, .user_name, #nick_id');
if (nickElement) {
foundNick = `Найдено в элементе: ${nickElement.tagName} | Текст: ${nickElement.textContent.trim()}`;
}
// 2. Поиск в ссылках (часто ник - это ссылка на профиль)
if (!foundNick) {
// Поиск ссылки, которая ведет на profile.php?id=2
const profileLink = document.querySelector('a[href*="profile.php?id=2"]');
if (profileLink) {
// Текст ссылки обычно и есть никнейм
foundNick = `Найдено в ссылке профиля: ${profileLink.textContent.trim()}`;
}
}
// 3. Финальный вывод
if (foundNick) {
alert(`✅ Успех! Ник найден:\n\n${foundNick}`);
} else {
alert(`❌ Неудача. Ник не найден в распространенных местах.
Попробуйте найти элемент с ником (F12 -> Inspector) и заменить '.user-nick-class' на его ID или класс.`);
}
});
});
</script>[/html]