HTML и JavaScript интеграция
Интеграция HTML и JavaScript
Различные способы подключения и использования JavaScript в HTML.
1. Способы подключения JavaScript
<!-- Внешний файл (рекомендуется) -->
<script src="app.js" defer></script>
<!-- Внутренний скрипт -->
<script>
document.addEventListener("DOMContentLoaded", function() {
console.log("DOM загружен");
});
</script>
<!-- Inline скрипт (избегать) -->
<button onclick="handleClick()">Нажми меня</button>
2. Доступ к элементам DOM
<div id="app" class="container">
<h1 data-page="home">Мое приложение</h1>
<button class="btn" data-action="save">Сохранить</button>
<ul class="items-list">
<li class="item">Элемент 1</li>
<li class="item">Элемент 2</li>
</ul>
</div>
<script>
// Различные способы выбора элементов
const app = document.getElementById("app");
const container = document.querySelector(".container");
const buttons = document.querySelectorAll(".btn");
const items = document.getElementsByClassName("item");
const heading = document.querySelector("h1[data-page]");
console.log("ID элемента:", app.id);
console.log("Классы:", app.className);
console.log("Data атрибут:", heading.dataset.page);
// Работа с коллекциями
buttons.forEach(button => {
console.log("Кнопка:", button.textContent);
});
// Преобразование HTMLCollection в массив
const itemsArray = Array.from(items);
itemsArray.forEach(item => {
console.log("Элемент:", item.textContent);
});
</script>
3. Создание и модификация элементов
<div id="dynamic-content"></div>
<button onclick="addNewItem()">Добавить элемент</button>
<button onclick="removeLastItem()">Удалить последний</button>
<script>
let counter = 1;
function addNewItem() {
const container = document.getElementById("dynamic-content");
// Создание нового элемента
const newItem = document.createElement("div");
newItem.className = "dynamic-item";
newItem.innerHTML = `
<h3>Динамический элемент ${counter}</h3>
<p>Создан: ${new Date().toLocaleTimeString()}</p>
<button onclick="removeThisItem(this)">Удалить</button>
`;
// Добавление в DOM
container.appendChild(newItem);
counter++;
// Прокрутка к новому элементу
newItem.scrollIntoView({ behavior: "smooth" });
}
function removeLastItem() {
const container = document.getElementById("dynamic-content");
const lastItem = container.lastElementChild;
if (lastItem) {
// Анимация удаления
lastItem.style.opacity = "0";
lastItem.style.transform = "translateX(-100px)";
setTimeout(() => {
container.removeChild(lastItem);
}, 300);
}
}
function removeThisItem(button) {
const item = button.closest(".dynamic-item");
if (item) {
item.style.opacity = "0";
item.style.transform = "translateX(100px)";
setTimeout(() => {
item.remove();
}, 300);
}
}
// Стили для динамических элементов
const style = document.createElement("style");
style.textContent = `
.dynamic-item {
border: 1px solid #3498db;
border-radius: 8px;
padding: 15px;
margin: 10px 0;
background: #f8f9fa;
transition: all 0.3s ease;
}
.dynamic-item:hover {
background: #e3f2fd;
transform: translateY(-2px);
}
.dynamic-item h3 {
margin: 0 0 10px 0;
color: #2c3e50;
}
.dynamic-item button {
background: #e74c3c;
color: white;
border: none;
padding: 5px 10px;
border-radius: 4px;
cursor: pointer;
}
`;
document.head.appendChild(style);
</script>
4. Обработка событий
<div class="interactive-demo">
<input type="text" id="text-input" placeholder="Введите текст...">
<button id="action-btn">Выполнить действие</button>
<div id="output"></div>
<div class="mouse-area">
Область для событий мыши
<div id="mouse-coords">Координаты: (0, 0)</div>
</div>
</div>
<script>
// Получение элементов
const textInput = document.getElementById("text-input");
const actionBtn = document.getElementById("action-btn");
const output = document.getElementById("output");
const mouseArea = document.querySelector(".mouse-area");
const mouseCoords = document.getElementById("mouse-coords");
// Обработчики событий для input
textInput.addEventListener("focus", function() {
this.style.borderColor = "#3498db";
this.style.boxShadow = "0 0 5px rgba(52, 152, 219, 0.5)";
});
textInput.addEventListener("blur", function() {
this.style.borderColor = "#bdc3c7";
this.style.boxShadow = "none";
});
textInput.addEventListener("input", function(event) {
const value = event.target.value;
output.textContent = `Вы ввели: ${value}`;
// Валидация в реальном времени
if (value.length < 3) {
output.style.color = "#e74c3c";
} else {
output.style.color = "#27ae60";
}
});
textInput.addEventListener("keydown", function(event) {
if (event.key === "Enter") {
performAction();
}
});
// Обработчик для кнопки
actionBtn.addEventListener("click", performAction);
// Обработчики для мыши
mouseArea.addEventListener("mousemove", function(event) {
const x = event.clientX - this.getBoundingClientRect().left;
const y = event.clientY - this.getBoundingClientRect().top;
mouseCoords.textContent = `Координаты: (${Math.round(x)}, ${Math.round(y)})`;
});
mouseArea.addEventListener("mouseenter", function() {
this.style.backgroundColor = "#e3f2fd";
});
mouseArea.addEventListener("mouseleave", function() {
this.style.backgroundColor = "";
mouseCoords.textContent = "Координаты: (0, 0)";
});
// Функция выполнения действия
function performAction() {
const value = textInput.value.trim();
if (value) {
output.innerHTML = `
<strong>Результат:</strong> ${value}
<br><small>Обработано: ${new Date().toLocaleTimeString()}</small>
`;
// Анимация
output.style.transform = "scale(1.05)";
setTimeout(() => {
output.style.transform = "scale(1)";
}, 200);
// Очистка input
textInput.value = "";
} else {
output.innerHTML = `
<span style="color: #e74c3c">
Пожалуйста, введите текст!
</span>
`;
}
}
// Стили для демо
const demoStyle = document.createElement("style");
demoStyle.textContent = `
.interactive-demo {
max-width: 500px;
margin: 20px auto;
padding: 20px;
border: 1px solid #bdc3c7;
border-radius: 8px;
}
#text-input {
width: 100%;
padding: 10px;
border: 2px solid #bdc3c7;
border-radius: 4px;
margin-bottom: 10px;
transition: all 0.3s ease;
}
#action-btn {
background: #3498db;
color: white;
border: none;
padding: 10px 20px;
border-radius: 4px;
cursor: pointer;
width: 100%;
}
#action-btn:hover {
background: #2980b9;
}
#output {
margin-top: 15px;
padding: 10px;
background: #ecf0f1;
border-radius: 4px;
min-height: 20px;
transition: all 0.2s ease;
}
.mouse-area {
margin-top: 20px;
padding: 30px;
border: 2px dashed #bdc3c7;
border-radius: 8px;
text-align: center;
cursor: crosshair;
transition: background-color 0.3s ease;
}
#mouse-coords {
margin-top: 10px;
font-family: monospace;
color: #7f8c8d;
}
`;
document.head.appendChild(demoStyle);
</script>