简体   繁体   中英

Prevent page scroll after click?

After clicking on the link, Click Me , the page scrolls back to the top. I do not want this. How can fix it?

Example: http://jsfiddle.net/Y6Y3Z/

Scroll-bar:

在此输入图像描述

    function myalert() {
        var result = true;
        //var hide = $('.alert').fadeOut(100);
        //var css = $('#appriseOverlay').css('display','none');
        var $alertDiv = $('<div class="alert">Are you sure you want to delete this item?<div class="clear"></div><button class="ok">no</button><button class="cancel">yes</button></div>');
        var link = this;
        $('body').append($alertDiv);
        $('.ok').click(function () {
            $('.alert').fadeOut(100);
            $('#appriseOverlay').css('display', 'none');
            callback(true, link);
        });
        $('.cancel').click(function () {
            $('.alert').fadeOut(100);
            $('#appriseOverlay').css('display', 'none');
            callback(false, link);
        });
        $alertDiv.fadeIn(100);
        $('#appriseOverlay').css('display', 'block');
        return result;
    };
$('.click').click(myalert);
    function callback(result, link) {
        //
        if(result){
        }
    }

The reason that it is going to the top of the page is because your anchor tag has a hash symbol as the href. The hash syntax allows you to refer to a named anchor in the document, with the link taking you to that place in the document. The default action for an anchor tag when you click on it and the href refers to a named anchor that doesn't exist is to go to the top of the page. To prevent this cancel the default action by returning false from the handler or using preventDefault on the event.

function myalert(e) {
    e.preventDefault(); // <-- prevent the default action

    ...

    return false; // <-- alternative way to prevent the default action.
};

You only need to change the "#" to "javascript:void(0)" on HTML code:

<a href="javascript:void(0)" class="click">Click Me</a>

Another solution is add a "/" after the "#":

<a href="#/" class="click">Click Me</a>

只是阻止默认功能(跳转到#marker)执行: http//jsfiddle.net/Y6Y3Z/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM