2025年7月7日 星期一

[網頁設計] 如何在網頁上設計一個按鈕連結How to create an HTML button that acts like a link?


在網頁上設計按鈕連結有幾種方法,以下是最常見的幾種方式:
1. 使用 <a> 標籤加上 CSS 樣式

這是最語義化的方法,將連結元素設計成按鈕外觀:

html

<a href="https://example.com" class="button">點擊我</a>

css

.button {
 display: inline-block;
 padding: 12px 24px;
 background-color: #007bff;
 color: white;
 text-decoration: none;
 border-radius: 4px;
 transition: background-color 0.3s;
}

.button:hover {
 background-color: #0056b3;
}


2. 使用 <button> 標籤包含連結

html

<button onclick="location.href='https://example.com'">點擊我</button>


3. 使用表單提交

html
<form action="https://example.com" method="get"> <button type="submit">點擊我</button> </form>

4. 使用 JavaScript 處理點擊事件

html
<button id="myButton">點擊我</button>

<script>
document.getElementById('myButton').addEventListener('click', function() {
 window.location.href = 'https://example.com';
});
</script>

推薦做法

對於簡單的連結按鈕,推薦使用第一種方法(<a> 標籤 + CSS),因為:
語義正確,搜索引擎友好
支援右鍵選單(新分頁開啟等)
無障礙性更好
即使 JavaScript 被禁用也能正常工作

如果需要在新分頁開啟連結,可以加上 target="_blank" 屬性:

html

<a href="https://example.com" class="button" target="_blank">點擊我</a>

這些方法都能創建功能完整的按鈕連結,你可以根據具體需求選擇最適合的方式。

沒有留言:

熱門文章