2012-02-10 120 views
0

奇怪的行为,我有一个简单的动画:与jQuery动画

$(function() { 
    $(".galleryButtonLeft").mousedown(function(){ 
     $("#theGallery").animate({ 
       marginLeft: "-=300px", 
     }, 1000); 
    }); 
}); 

theGallery只是一个divposition:relative

没什么特别的:

  <div style="position:relative"> 
       <img/> 
     </div> 

当我点击我的galleryButtonLeft将其300px向左移动,页面立即去顶,如果我有我的浏览器unmaximized并滚动到页面的中间在我的画廊坐落。我希望页面保持在原来的位置,并且每次单击该按钮时都不会跳转到顶部。我怎么做?

+0

小问题:'300px'后面会出现一个尾随的逗号,这会在某些版本的IE中导致错误。 – Sparky 2012-02-10 18:52:23

+0

您还应该提供相关位的HTML代码。 – Sparky 2012-02-10 18:53:19

+0

您可能在按钮内部有一个'href =“#”',当点击它时,会将您带回到页面的顶部。请参阅下面的@ gion_13回答。 – Sparky 2012-02-10 18:56:56

回答

2

我将假设.galleryButtonLeft元素与它们的href属性的链接设置为散列(#)。无论是return falseevent.preventDefault()取消链接(S)的默认行为:

$(function() { 
    $(".galleryButtonLeft").mousedown(function(){ 
     $("#theGallery").animate({ 
      marginLeft: "-=300px"//notice I removed the trailing comma here, it'll come back to haunt you if you don't (some browsers throw errors for these) 
     }, 1000); 
    }).click(false);//this returns false for any click event for the/these element(s), stopping the default behavior of the element(s) 
}); 

返回false内一个jQuery事件处理的是同样的事情,呼吁event.preventDefault()event.stopPropagation()

如果你想使用event.preventDefault()而不是返回false,那么你必须传递在event对象在匿名函数(事件处理程序):

$(function() { 
    $(".galleryButtonLeft").mousedown(function(){ 
     event.preventDefault(); 
     $("#theGallery").animate({ 
      marginLeft: "-=300px"//notice I removed the trailing comma here, it'll come back to haunt you if you don't (some browsers throw errors for these) 
     }, 1000); 
    }).click(function (event) { 
     event.preventDefault(); 
    }); 
}); 

注意,您可以在事件的任何地方拨打event.preventDefault()处理程序,但返回false必须是最后一次调用,因为它会停止执行事件处理程序。

+0

这工作到完美。非常感谢 – BoundForGlory 2012-02-10 20:09:58

+0

@ user1202717不客气。 – Jasper 2012-02-10 20:12:39

2

如何添加

/*...*/mousedown(function(e){e.preventDefault(); /*...*/ 

$(".galleryButtonLeft").click(function(e){e.preventDefault();}); 

我认为这个问题可能是你的触发器(.galleryButtonLeft)是它具有href属性设置为东西起动的元素与#。这样,当你点击链接时,浏览器栏中的哈希值会发生变化,从而使浏览器跳起来。