<fieldset>
元素可以通过 form
属性与页面上的任何 <form>
元素关联,即使它们在 HTML 结构上不是父子关系。
<!DOCTYPE html>
<html>
<body>
<!-- 表单在页面顶部 -->
<form id="userForm" action="/submit" method="post">
<button type="submit">提交表单</button>
</form>
<!-- 其他内容 -->
<div class="content">
<h2>页面其他内容</h2>
<p>这里有很多其他元素...</p>
</div>
<!-- fieldset 在页面底部,但通过 form 属性关联到上面的表单 -->
<fieldset form="userForm">
<legend>用户详细信息</legend>
<input type="text" name="username" placeholder="用户名" required>
<input type="email" name="email" placeholder="邮箱" required>
<input type="tel" name="phone" placeholder="电话">
</fieldset>
<!-- 另一个独立的 fieldset,也关联到同一个表单 -->
<fieldset form="userForm">
<legend>地址信息</legend>
<input type="text" name="address" placeholder="地址">
<input type="text" name="city" placeholder="城市">
</fieldset>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<style>
.form-section { margin: 20px 0; }
.sidebar { float: right; width: 300px; }
.main-content { margin-right: 320px; }
</style>
</head>
<body>
<!-- 主表单 -->
<form id="orderForm" action="/submit-order" method="post">
<h1>订单提交</h1>
<button type="submit">确认订单</button>
</form>
<div class="main-content">
<h2>商品信息</h2>
<!-- 商品选择区域,关联到订单表单 -->
<fieldset form="orderForm" class="form-section">
<legend>选择商品</legend>
<label>
<input type="checkbox" name="products" value="laptop">
笔记本电脑 - ¥5000
</label>
<label>
<input type="checkbox" name="products" value="mouse">
无线鼠标 - ¥100
</label>
</fieldset>
</div>
<div class="sidebar">
<!-- 侧边栏的配送信息,也关联到同一个表单 -->
<fieldset form="orderForm">
<legend>配送信息</legend>
<input type="text" name="address" placeholder="配送地址" required>
<select name="delivery">
<option value="standard">标准配送</option>
<option value="express">快速配送</option>
</select>
</fieldset>
<!-- 支付方式 -->
<fieldset form="orderForm">
<legend>支付方式</legend>
<label>
<input type="radio" name="payment" value="alipay">
支付宝
</label>
<label>
<input type="radio" name="payment" value="wechat">
微信支付
</label>
</fieldset>
</div>
</body>
</html>
物理分离,逻辑关联:fieldset 可以在 HTML 结构上与 form 分离,但通过
form
属性在逻辑上关联表单提交包含所有关联控件:当提交表单时,所有通过
form
属性关联的 fieldset 中的表单控件都会被包含在提交数据中灵活的页面布局:这种方式允许更灵活的页面布局,表单控件可以分布在页面的不同位置
disabled 属性的影响:如果 fieldset 设置了
disabled
属性,其中的所有表单控件都会被禁用,且不会包含在表单提交中