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>
原文地址:https://www.cnblogs.com/sipher/p/11068187.html