HTML onhashchange 事件屬性
HTML onhashchange 事件屬性在 HTML 文件的 URL 錨部分發生變化時觸發。
語法
以下為語法 −
<tagname onhashchange=”script”></tagname>
我們看一個 HTML onhashchange 事件屬性的示例−
示例
<!DOCTYPE html> <html> <head> <style> body { color: #000; height: 100vh; background-color: #FBAB7E; background-image: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%); text-align: center; } .btn { background: #db133a; border: none; color: #fff; height: 2rem; padding: 8px 10px; } </style> </head> <body onhashchange="hashChange()"> <h1>HTML onhashchange Event Attribute Demo</h1> <button class="btn" onclick="change()">Set Hash</button> <p class="msg"></p> <script> function change() { location.hash = "newHashPart"; document.querySelector('.msg').innerHTML = 'The hash part of the URL is: ' + location.hash; } function hashChange() { document.body.style.background = 'lightblue'; } </script> </body> </html>
輸出
點選“設定 Hash”按鈕向當前 URL 設定新的 hash,並觀察 onhashchange 事件屬性如何工作
廣告