【问题标题】:Why isn't preventDefault working for jQuery?为什么 preventDefault 不能用于 jQuery?
【发布时间】:2010-10-18 16:34:16
【问题描述】:

我似乎无法让 preventDefault() 与以下代码一起使用...浏览器在单击后仍希望跳转到页面顶部。有关如何解决此问题的任何想法?

$('#controls a').click(function(event){

 event.preventDefault();

 var r = $(this).attr('rel');

 var c = $('#container').attr('class');
 // Prevent redundant actions
 if (r != c) {
  // Toggle 'active' class to show selection
  $('#controls a').removeClass('active');
  $(this).addClass('active');
  // Fade out function then callback to change the view mode
  $('#container').fadeOut(100, function(){    
     $('#container').removeAttr('class');
     $('#container').addClass(r);
     // Fade the container back in
     $('#container').fadeIn(100);
  });
 }

}); //end list view

【问题讨论】:

  • 能否添加相关的HTML,确定页面没有JS错误?
  • 剩下的代码能用吗?
  • 点击后您的 URL 是否附加了 #(或其他任何内容...)?如果没有,preventDefault 工作正常...

标签: jquery events event-handling


【解决方案1】:

问题(可能,这部分是猜测)不是preventDefault(),但事实上您的页面在一段时间内的整体高度内容较少(准确地说是 13 毫秒),请更改你的动画,所以它淡出,但没有得到 display: none; 的帧,像这样:

$('#container').animate({ opacity: 0 }, 100, function(){    
  $('#container').removeAttr('class');
  $('#container').addClass(r);
  // Fade the container back in
  $('#container').animate({ opacity: 1 }, 100);
});

这样一来,您的#container 的高度暂时是0,导致页面向上滚动只是因为页面整体变短了。

【讨论】:

  • 哦,我怎么会错过你是正确的,只是添加了最小高度来测试这个理论,它工作你钉了它谢谢
  • @Terry - 上述解决方案是否为您解决了问题?
猜你喜欢
  • 2013-01-18
  • 1970-01-01
  • 2021-05-09
  • 1970-01-01
  • 1970-01-01
  • 2015-03-27
  • 1970-01-01
  • 2023-03-25
  • 1970-01-01
相关资源
最近更新 更多