jQuery 控制網頁捲軸移動 & Ignore link '#' method jump action
$('a.gotoheader').click(function(){ // 讓捲軸移動到 0 的位置 $('html, body').scrollTop(0); // ignore link "#" method return false; });
//在scroll時加入動畫效果 $('a.gotoheader').click(function(){ // 修正 Opera 問題 var $body = (window.opera) ? (document.compatMode == "CSS1Compat" ? $('html') : $('body')) : $('html,body'); $body.animate({ scrollTop: 0 }, 600); return false; });
//scroll到頁面指定的位置,最後再加上easeOutBounce 的動畫效果 $('a.gotoheader').click(function(){ // 修正 Opera 問題 var $body = (window.opera) ? (document.compatMode == "CSS1Compat" ? $('html') : $('body')) : $('html,body'); $body.animate({ scrollTop: $('#header').offset().top }, 2000, 'easeOutBounce'); return false; });
想要ignore link "#" method, 當click一個link時,page不要跳轉,可使用
<a href="javascript:void(0);">Example</a>
來代替
<a href="#">Example</a>
也可以使用上面例子中提到在,onclick事件觸發後的function中 return false;
另外一種方法就是使用 event.preventDefault(); 取消事件的預設行為
<!DOCTYPE html> <html> <head> <title>preventDefault example</title> </head> <body> <p>Please click on the checkbox control.</p> <form> <label for="id-checkbox">Checkbox</label> <input type="checkbox" id="id-checkbox"/> </form> <script> document.querySelector("#id-checkbox").addEventListener("click", function(event){ alert("preventDefault will stop you from checking this checkbox!") event.preventDefault(); }, false); </script> </body> </html>
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步