简体   繁体   English

Jquery:<a>链接点击 preventDefault() 不起作用?</a>

[英]Jquery: <a> link click preventDefault() not working?

I'm trying to prevent a link click from firing if accidentally touched while scrolling in mobile?如果在移动设备中滚动时意外触摸,我试图防止链接点击触发? I have never tried something like this before and am having trouble getting it to work right.我以前从未尝试过这样的事情,并且无法正常工作。 I am testing this on a desktop for the time being.我暂时在桌面上测试这个。 My buttons are structured similar to:我的按钮结构类似于:

<a href="http://www.google.com">
    <div style="width:100%;height:80px;margin-bottom:50px;">test</div>
</a>

I am trying to use the preventDefault() function to override default click actions and check if a the page is being scrolled, or it the click was accidental before allowing it to work.我正在尝试使用 preventDefault() 函数来覆盖默认的点击操作并检查页面是否正在滚动,或者在允许它工作之前点击是意外的。 The logic to check seems to work, however the links navigate on click no matter what i do.检查的逻辑似乎有效,但是无论我做什么,链接都会在单击时导航。 I assume this has something to do with the links behaviour being propogated to the child div, but am not sure.我认为这与传播到子 div 的链接行为有关,但我不确定。

Below is my script, the problem is in the last $('a').click();下面是我的脚本,问题出在最后一个 $('a').click(); function.功能。

UPDATE:更新:

I still need a better way to do it using just the $('a') selector if anyone knows how.如果有人知道怎么做,我仍然需要一个更好的方法来使用 $('a') 选择器。 Kind of a hack but, if i change the selector to $('a>div') and change the 'targetLink' to $(this).parent().attr('href') it seems to work, Is there a way to do this using $('a') only because some of my buttons have more children.有点像黑客但是,如果我将选择器更改为 $('a>div') 并将 'targetLink' 更改为 $(this).parent().attr('href') 它似乎有效,是否有使用 $('a') 这样做的方法只是因为我的一些按钮有更多的孩子。

//Mobile accidental scroll click fix:---
//- prevent clicked link from executing if user scrolls after mousedown, until next mousedown.
//- prevent clicked link from executing if user is still scrolling and mouse is down(for slow scrolls)

$(document).ready(function(){
    var self = this,
        scrolling = false,
        mouseDown = false,
        scrollAfterPress = false;
        scrollDelay = 1500,
        linkConditionCheckDelay = 700;

        $(window).scroll(function() {
            self.scrolling = true;
            console.log('scrolling:' + self.scrolling);
            clearTimeout( $.data( this, "scrollCheck" ) );
            $.data( this, "scrollCheck", setTimeout(function() {
                self.scrolling = false;
                console.log('scrolling:' + self.scrolling);
            }, scrollDelay) );

        });

        $(document).mousedown(function(){
                self.scrollAfterPress = false;
                int00 = setInterval(function() { checkScrollAfterPress(); }, 100);//execute every 100ms (while mouse is down)
                self.mouseDown = true;
                console.log('mousedown:'+ self.mouseDown);
            }).mouseup(function(){
                clearInterval(int00);
                self.mouseDown = false; 
                console.log('mousedown:'+ self.mouseDown);
            });

        function checkScrollAfterPress(){
            if(self.scroll === true){
                self.scrollAfterPress = true;
            }
        }

        $('a').click(function(e){
             //prevent default click event behaviour
            var targetLink = $(this).attr('href');
            console.log('clicked on:'+targetLink);
            setTimeout(function() {
                    if(!self.scrolling && !self.mouseDown && !self.scrollAfterPress && targetLink !== undefined){
                        window.location.href = targetLink;
                    }
                }, linkConditionCheckDelay); //add small delay to prevent immeditiate responses between mouse up and start of scroll.
            e.stopPropagation();
            e.preventDefault();
        });
});

You can use return false or e.preventDefault您可以使用return falsee.preventDefault

But when you click on that link why your adding window.location.href = targetLink;但是当你点击那个链接时,为什么你添加window.location.href = targetLink; ?? ?? which will redirect the user to the given location.Same as link这会将用户重定向到给定的位置。与链接相同

Try my code below i have removed it.试试我下面的代码,我已经删除了它。

 $(document).ready(function(){ var self = this, scrolling = false, mouseDown = false, scrollAfterPress = false; scrollDelay = 1500, linkConditionCheckDelay = 700; $(window).scroll(function() { self.scrolling = true; console.log('scrolling:' + self.scrolling); clearTimeout( $.data( this, "scrollCheck" ) ); $.data( this, "scrollCheck", setTimeout(function() { self.scrolling = false; console.log('scrolling:' + self.scrolling); }, scrollDelay) ); }); $(document).mousedown(function(){ self.scrollAfterPress = false; int00 = setInterval(function() { checkScrollAfterPress(); }, 100);//execute every 100ms (while mouse is down) self.mouseDown = true; console.log('mousedown:'+ self.mouseDown); }).mouseup(function(){ clearInterval(int00); self.mouseDown = false; console.log('mousedown:'+ self.mouseDown); }); function checkScrollAfterPress(){ if(self.scroll === true){ self.scrollAfterPress = true; } } $('a').click(function(e){ //prevent default click event behaviour var targetLink = $(this).attr('href'); console.log('clicked on:'+targetLink); setTimeout(function() { if(!self.scrolling && !self.mouseDown && !self.scrollAfterPress && targetLink !== undefined){ //window.location.href = targetLink; } }, linkConditionCheckDelay); //add small delay to prevent immeditiate responses between mouse up and start of scroll. return false; }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="http://www.google.com"> <div style="width:100%;height:80px;margin-bottom:50px;">test</div> </a>

I will suggest another approach and use jQuery Mobile Events .我会建议另一种方法并使用jQuery Mobile Events Something like this:像这样的东西:
*untested, but is the idea *未经测试,但这是想法

// set global var 'locked'
var locked = false;

// locked var true while scrolling
jQuery(document).on('scrollstart', function() { locked = true; });

// locked var back to false when finish
jQuery(document).on('scrollstop', function() { locked = false; });

// bind 'tap' & 'click' events to 'a' tag
jQuery(document).on('tap click', 'a', function(event) {
    // But before proceed, check locked var
    if (locked) {
        event.preventDefault;
        return false;
    } else {
        // ok, proceed with the click and further events...
    }
});

Docs/ref: scrollstart event scrollstop event tap event vclick event .click()文档/参考: scrollstart 事件scrollstop 事件点击事件vclick 事件 .click ()

Use in your $'a'.click(function(e){...} part return false; to prevent the default behavior.在您的$'a'.click(function(e){...}部分使用return false;以防止默认行为。

In your case:在你的情况下:

$('a').click(function(e){
        var targetLink = $(this).attr('href');
        console.log('clicked on:'+targetLink);
        setTimeout(function() {
                if(!self.scrolling && !self.mouseDown && !self.scrollAfterPress && targetLink !== undefined){
                    window.location.href = targetLink;
                }
            }, linkConditionCheckDelay); 
        return false;//Stops default behavior
    });

Perhaps there is something I am missing, but I do not see why your code cannot be made as simple as the following:也许我遗漏了一些东西,但我不明白为什么你的代码不能像下面这样简单:

$(document).ready(function () {
    var is_scrolling = false;
    var timeout = null;

    $(window).scroll(function () {
        is_scrolling = true;
        if (timeout) {
            clearTimeout(timeout);   
        }
        timeout = setTimeout(function () {
            is_scrolling = false;
        }, 1500);
    });

    $('a').click(function (e){
        if (is_scrolling) {
            e.preventDefault();
        }
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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