操作標籤樣式
`document.querySelector()` 會取得符合 CSS 選擇器的**第一個元素**,取得後可透過元素的 `style` 物件修改 inline CSS。
```javascript
const 元素 = document.querySelector('CSS 選擇器');
元素.style.CSS屬性 = '值';
```
注意:
- CSS 的 `background-color` 在 JavaScript 中要寫成 `backgroundColor`
- `font-size` 要寫成 `fontSize`
- 寬度、高度、間距等通常要加單位,例如 `px`、`%`
- `querySelector()` 找不到元素時會回傳 `null`
---
## 範例一:修改公告區塊的背景色與文字樣式
```html
<div class="notice">
今日特價商品,限時優惠!
</div>
<script>
const notice = document.querySelector('.notice');
if (notice) {
notice.style.backgroundColor = '#fff3cd';
notice.style.color = '#856404';
notice.style.padding = '15px';
notice.style.border = '1px solid #ffeeba';
notice.style.fontSize = '18px';
}
</script>
```
執行後,`.notice` 元素會直接產生類似以下的 inline CSS:
```html
<div class="notice"
style="background-color: rgb(255, 243, 205); color: rgb(133, 100, 4); ...">
```
---
## 範例二:將錯誤訊息隱藏,並修改輸入框外觀
```html
<input class="username" type="text" placeholder="請輸入帳號">
<p class="error-message">帳號格式錯誤</p>
<script>
const usernameInput = document.querySelector('.username');
const errorMessage = document.querySelector('.error-message');
if (usernameInput) {
usernameInput.style.border = '2px solid red';
usernameInput.style.backgroundColor = '#fff0f0';
usernameInput.style.padding = '8px';
}
if (errorMessage) {
errorMessage.style.color = 'red';
errorMessage.style.fontWeight = 'bold';
errorMessage.style.display = 'block';
}
</script>
```
這個範例會將輸入框標示為錯誤狀態,並讓錯誤訊息顯示為紅色粗體。
也可以使用 `style.setProperty()` 修改 CSS 屬性:
```javascript
const box = document.querySelector('.notice');
if (box) {
box.style.setProperty('background-color', 'lightblue');
box.style.setProperty('font-size', '20px');
}
```
如果 CSS 屬性名稱包含連字號,使用 `setProperty()` 時可以直接保留原本的 CSS 寫法。
相關學習地圖、教學課程
F2E 網站前端工程