> For the complete documentation index, see [llms.txt](https://docs.webmix.cc/javascript-web/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.webmix.cc/javascript-web/5.-shi-jian/5.4-hua-shu-shi-jian.md).

# 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：垂直方向滑動了多少距離。

示意圖：

![](https://410574885-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MAt7E5uEtF03Nlaa53X%2Fuploads%2FMm6Jd6UZewYk9M4c94DG%2Fpagey_minus_scrolly.png?alt=media\&token=ac5ef137-fd4b-475e-8871-4c427ce7886d)

介紹 position: fixed 這個 css：

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

參考作法：

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