# 5.7 滑鼠相關事件

## click 、dblclick 與事件冒泡狀況(Event Bubble Up)

click 事件的寫法，使用 **`.addEventListener()`**：

```javascript
var my_el = document.getElementById("my_el");
my_el.addEventListener("click", function(){
  // 點擊後，要執行的程式...
});
```

範例(click)：

{% embed url="<https://codepen.io/carlos411/pen/BaKpJKO>" %}

範例(dblclick)：

{% embed url="<https://codepen.io/carlos411/pen/NWNdXvJ>" %}

如果要停止事件冒泡狀況發生，在正確的位置執行以下程式：

```javascript
e.stopPropagation();
```

### 範例：lightbox (燈箱)

{% embed url="<https://codepen.io/carlos411/pen/mdpYWmq>" %}

## 其它滑鼠相關事件

### mousedown、mouseup

mousedown：滑鼠按壓下去時觸發。(會發生冒泡狀況)

mouseup：滑鼠按壓下去放開時觸發。(會發生冒泡狀況)

範例(不用背，要會觀察)：

{% embed url="<https://codepen.io/carlos411/pen/ZEWLvBY>" %}

### mouseover、mouseout

mouseover：滑鼠移入時觸發。(會發生冒泡狀況)

mouseout：滑鼠移出時觸發。(會發生冒泡狀況)

範例：

{% embed url="<https://codepen.io/carlos411/pen/zYqNpNq>" %}

### mouseenter、mouseleave

mouseenter：滑鼠移入時觸發。(不會發生冒泡狀況)

mouseleave：滑鼠移出時觸發。(不會發生冒泡狀況)

範例：

{% embed url="<https://codepen.io/carlos411/pen/PoNWEpB>" %}

### mousemove

說明：滑鼠游標在元素上移動時觸發。(會發生事件冒泡狀況)

範例：

{% embed url="<https://codepen.io/carlos411/pen/mdPRpmL>" %}

### 範例：圖片跟著滑鼠移動

針對 document 綁定 mousemove 事件。

e.pageX：滑鼠距離頁面最左側的距離。

e.pageY：滑鼠距離頁面最上方的距離。

window\.scrollY：垂直方向滑動了多少距離。

示意圖：

![](/files/1Y1WBLye2sx4DIfTHmMB)

介紹 position: fixed 這個 css：

{% embed url="<https://codepen.io/carlos411/pen/ogzRpmB>" %}

參考作法：

{% embed url="<https://codepen.io/carlos411/pen/RwaJYKK>" %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.webmix.cc/javascript-web/5.-shi-jian/5.4-hua-shu-shi-jian.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
