jQuery动画的奇怪行为
我有一个简单的动画:jQuery动画的奇怪行为,jquery,Jquery,我有一个简单的动画: $(function () { $(".galleryButtonLeft").mousedown(function(){ $("#theGallery").animate({ marginLeft: "-=300px", }, 1000 ); }); }); Gallery只是一个div,具有position:relative 没什么特别的: <div style="p
$(function () {
$(".galleryButtonLeft").mousedown(function(){
$("#theGallery").animate({
marginLeft: "-=300px",
}, 1000 );
});
});
Gallery只是一个div
,具有position:relative
没什么特别的:
<div style="position:relative">
<img/>
</div>
当我点击我的galleryButtonLeft向左移动300px
时,如果我的浏览器未最大化,页面会立即转到顶部,并滚动到我的gallery所在页面的中间。我希望页面保持在原来的位置,而不是每次单击按钮都跳到顶部。我该怎么做?如何添加
/*...*/mousedown(function(e){e.preventDefault(); /*...*/
或
我认为问题可能在于您的触发器(.galleryButtonLeft
)是一个元素,它的href
属性设置为以#
开头。这样,当您单击链接时,浏览器栏中的散列会发生变化,使浏览器跳起来。添加
/*...*/mousedown(function(e){e.preventDefault(); /*...*/
或
我认为问题可能在于您的触发器(
.galleryButtonLeft
)是一个元素,它的href
属性设置为以#
开头。这样,当您单击链接时,浏览器栏中的哈希值会发生变化,使浏览器跳转。我假设.galleryButtonLeft
元素是链接,其href
属性设置为散列(#
)。return false
或event.preventDefault()
取消链接的默认行为:
在jQuery事件处理程序中返回false
与调用event.preventDefault()
和event.stopPropagation()
是一样的
如果要使用event.preventDefault()
而不是返回false
,则必须在匿名函数(事件处理程序)中传入event
对象:
请注意,您可以在事件处理程序中的任何位置调用
event.preventDefault()
,但是返回false必须是最后调用的内容,因为它将停止事件处理程序的执行。我假设.galleryButtonLeft
元素将链接的href
属性设置为哈希(#
)的是/是链接。return false
或event.preventDefault()
取消链接的默认行为:
在jQuery事件处理程序中返回false
与调用event.preventDefault()
和event.stopPropagation()
是一样的
如果要使用event.preventDefault()
而不是返回false
,则必须在匿名函数(事件处理程序)中传入event
对象:
请注意,您可以在事件处理程序中的任何位置调用event.preventDefault(),但是返回false
必须是最后一个调用,因为它将停止事件处理程序的执行。次要问题:在300px
后面有一个逗号,这将在IE的某些版本中导致错误。您还应该为相关位提供HTML代码。您可能有一个href=“#”
在您的按钮内,单击该按钮将返回页面顶部。请参阅下面@gion_13的答案。附带问题:在300px
后面有一个逗号,这将导致IE的某些版本出现错误。您还应该提供相关位的HTML代码。您的按钮中可能有一个href=“#”
,单击该按钮后,将返回页面顶部。见下文@gion_13的答案。
$(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)
});
$(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();
});
});