如何為沒有href屬性的連結設定指標樣式的游標?


我們可以使用HTML中的<a>標籤向網頁新增連結。<a>元素的預設游標樣式是指標,但是從<a>標籤中移除href屬性會改變游標樣式。

因此,在本教程中,我們將學習如何為沒有href屬性的<a>標籤保留指標樣式的游標。

使用者可以按照下面的示例檢視<a>元素的預設游標樣式。

示例

在下面的示例中,我們使用了<a>標籤建立了三個不同的連結。

在輸出中,我們可以觀察到,當我們將滑鼠懸停在第一個連結上時,游標變成指標,因為它包含href屬性;對於第二個連結,游標也變成指標,因為它也包含一個空字串值的href屬性;當我們將滑鼠懸停在第三個連結上時,游標樣式會改變,因為它不包含href屬性。

<html>
<body>
   <h2>Cursor pointer on the anchor texts</h2>
   <a href = "https://tutorialspoint.tw/index.htm"> tutorialspoint</a>
   <br> <br>
   <a href = ""> Cursor pointer </a>
   <br> <br>
   <a> No cursor pointer </a>
</body>
</html>

現在,使用者瞭解了當我們從<a>標籤中移除href屬性時游標樣式是如何變化的。

下面,我們將檢視為沒有href屬性的連結設定指標游標的示例。

語法

使用者可以按照以下語法使用css為沒有href屬性的連結設定指標游標。

<style>
  .pointer {
     cursor: pointer;
   }
</style>

在上面的語法中,“pointer”是分配給<a>元素的類,我們已經更改了包含“pointer”類的元素的指標樣式。

示例

在下面的示例中,我們建立了兩個不同的<a>元素,並將“pointer”類分配給這兩個元素。在<head>部分,我們為網頁添加了內聯樣式。我們在<style>標籤中訪問了“pointer”類,並添加了“cursor: pointer”CSS來新增指標樣式的游標。

<html>
<head> 
   <style>
      .pointer {
         cursor: pointer;
      }
   </style>
</head>
<body>
   <h2>Using the CSS to set the cursor pointer on the anchor texts in the link without the href attribute </h2>
   <a class = "pointer"> cursor pointer </a>
   <br> <br>
   <a class = "pointer"> No href attribute </a>
</body>
</html>

示例

在下面的示例中,我們使用了“cursor: pointer”樣式將沒有href屬性的<a>元素的游標樣式設定為指標,就像示例2一樣,但是我們將內聯CSS應用於<a>標籤。

<html>
<body>
   <h3>Using the inline CSS to set cursor pointer on the anchor texts in the link without the href attribute. </h3>
   <a style = "cursor: pointer;"> cursor pointer </a>
</body>
</html>

示例

在下面的示例中,我們使用了“onmouseover”事件屬性。每當滑鼠指標移到<a>標籤上時,它都會呼叫分配給它的回撥函式。在這裡,我們分配了一行CSS,而不是分配回撥函式。

因此,每當使用者將滑鼠懸停在沒有href屬性的<a>標籤上時,它都會將游標樣式設定為指標。

<html>
<body>
   <h3>Using the onmouseover event and css to add cursor pointer on the anchor texts in the link without herf attribute </h3>
   <a onmouseover = "this.style.cursor='pointer'"> Link 1 </a> <br>
   <a onmouseover = "this.style.cursor='pointer'"> Link 2 </a> <br>
   <a onmouseover = "this.style.cursor='pointer'"> Link 3 </a> <br>
   <a onmouseover = "this.style.cursor='pointer'"> Link 4 </a> <br>
</body>
</html> 

示例

在下面的示例中,我們使用了帶有href屬性的<a>標籤,但是我們將空字串作為href屬性的值分配給了它。因此,它會自動作為空連結工作,併為<a>標籤設定指標游標。

<html>
<body>
   <h3>Assigning the empty value to the href attribute to add cursor pointer </i> on the anchor texts</h3>
   <a href = ""> Link 1 </a> <br>
   <a href = ""> Link 2 </a> <br>
</body>
</html>

在本教程中,我們學習瞭如何為沒有href屬性的連結將游標樣式設定為指標。我們使用了CSS來更改游標樣式。此外,我們還使用了onmouseover事件屬性來檢測滑鼠懸停事件並相應地更改游標樣式。

更新於:2023年2月22日

2K+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告