上一篇
html标签js
- 行业动态
- 2025-05-01
- 2
HTML标签构建页面结构,JS通过DOM操作实现交互,二者结合实现
HTML基础结构
HTML(超文本标记语言)是网页的骨架,通过标签定义内容结构,基本结构如下:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8">页面标题</title> <link rel="stylesheet" href="style.css"> <script src="script.js"></script> </head> <body> <!-网页内容 --> </body> </html>
常用HTML标签
作用 | 示例 | |
---|---|---|
<div> | 容器,用于布局 | <div class="container"> |
<span> | 器,修饰文本 | <span style="color:red"> |
<a> | 超链接 | <a href="https://example.com"> |
<img> | 图片 | <img src="image.jpg" alt="描述"> |
<ul> /<ol> | 无序/有序列表 | <ul><li>项目</li></ul> |
<table> | 表格 | <table><tr><td>数据</td></tr></table> |
JavaScript基础
JavaScript(JS)是网页的脚本语言,用于实现交互逻辑。
基础语法
- 变量声明:
let name = "Alice"; // 块级作用域 const pi = 3.14; // 常量 var age = 25; // 函数作用域(老旧写法)
- 函数定义:
function greet(msg) { console.log(msg); } greet("Hello World");
操作DOM
通过JS修改HTML元素:
// 获取元素 const btn = document.getElementById("myBtn"); const list = document.querySelector(".item-list"); btn.innerText = "Clicked!"; // 添加节点 const newItem = document.createElement("li"); newItem.textContent = "New Item"; list.appendChild(newItem);
HTML与JS的结合
事件处理
为HTML元素绑定事件,触发JS逻辑:
<button id="myBtn">点击我</button> <script> document.getElementById("myBtn").addEventListener("click", function() { alert("按钮被点击!"); }); </script>
根据用户操作更新页面:
const input = document.querySelector("input"); input.addEventListener("input", function() { const output = document.querySelector(".output"); output.textContent = "输入内容:" + this.value; });
常见问题与解答
问题1:如何用JS修改元素的样式?
解答:通过element.style
属性直接设置CSS:
const box = document.querySelector(".box"); box.style.backgroundColor = "blue"; box.style.width = "200px";
问题2:如何验证表单输入是否为空?
解答:监听表单提交事件,检查输入值:
<form id="myForm"> <input type="text" id="username" required> <button type="submit">提交</button> </form> <script> document.getElementById("myForm").addEventListener("submit", function(e) { const username = document.getElementById("username").value; if (!username) { e.preventDefault(); // 阻止提交 alert("用户名不能为空!"); } });