我正在解决一个问题,我想用一个专门分配给元素的事件监听器覆盖全局 onscroll 事件监听器。
这是一个例子。
$("a").on('click', function(){
console.log('Clicked');
$('html,body').animate({scrollTop:50}, 1000);
var count = 0;
$(window).on('scroll', function(){
if(count < 5)
{
console.log('Scrolling via link...');
}
count++;
});
});
var globalCount = 0;
$(window).on('scroll', function(){
if(globalCount < 5)
{
console.log('Scrolling...');
}
globalCount++;
});
body{min-height:2000px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#">Link</a>
如何阻止 console.log('Scrolling...') 运行?
最佳答案
你可以试试event.stopPropagation()
$("a").on('click', function(){
console.log('Clicked');
$('html,body').animate({scrollTop:50}, 1000);
var count = 0;
$(window).on('scroll', function(event){
if(count < 5)
{
console.log('Scrolling via link...');
}
count++;
//stop propagation stops the bubbling of the event down to further event handlers.
event.stopPropagation();
});
});
var globalCount = 0;
$(window).on('scroll', function(){
if(globalCount < 5)
{
console.log('Scrolling...');
}
globalCount++;
});
body{min-height:2000px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#">Link</a>
关于javascript - 您可以使用另一个覆盖 "onscroll"监听器吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40110900/