单击后阻止页面滚动? [英] Prevent page scroll after click?

查看:381
本文介绍了单击后阻止页面滚动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

点击链接后,点击我,页面滚动回到顶部。我不想要这个。如何解决?

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

示例: http://jsfiddle.net/Y6Y3Z/

滚动条:

    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){
        }
    }


推荐答案

它到达页面顶部的原因是因为你的锚标签有一个哈希符号作为href 。哈希语法允许您引用文档中的命名锚点,链接将您带到文档中的该位置。单击锚标记并且href引用不存在的命名锚点时,默认操作是转到页面顶部。要防止此操作,请通过从处理程序返回false或在事件上使用 preventDefault 来取消默认操作。

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.
};

这篇关于单击后阻止页面滚动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆