gpt4 book ai didi

javascript - jQuery 动画在 anchor 标记或 anchor 标记子项中不起作用

转载 作者:行者123 更新时间:2023-11-28 12:20:20 25 4
gpt4 key购买 nike

我花了一天的大部分时间来追踪我在 jQuery 动画方面遇到的问题。将 jQuery.animate() 应用于 anchor 元素或 anchor 元素内的子元素似乎存在问题,至少在移动动画方面。我已将问题归结为一个相当简单的示例来说明问题:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script>
var foo = {};

function TestMove(newx, newy) {
this.newx = newx;
this.newy = newy;
}

TestMove.prototype = {
movex:function () {
$("#newsec").animate({left: this.newx + "px"});
},
movey:function () {
$("#newsec").animate({top: this.newy + "px"});
}
}

function bar() {
foo[1].movex();
foo[1].movey();
}

function init() {
foo[1] = new TestMove(200,200);
}
</script>
</head>
<body onload="init()">
<a href="" style="position: relative;">
<div style="position: relative; height: 50px; width: 50px; background-color: red;" id="newsec" onclick="bar()"></div>
</a>
</body>
</html>

无论我是将 id 属性和 onclick 事件处理程序调用放在 标记中还是在其中的

中,动画都不起作用。另一方面,如果我完全删除 元素标签,则动画在
元素上按预期工作。

有人知道为什么会这样吗?

这个问题几乎没有实际意义,因为我可以很容易地在工作页面中使用

元素来做我也可以用 元素做的事情。在工作代码(复杂得多)中,我在 anchor 元素上使用 event.preventDefault() 以便链接和其他操作由显式事件处理程序驱动,这也可以从
完成。我相信我什至可以在将鼠标悬停在
上时更改指针图标,以便它在这方面也模仿真正的 anchor 。

最佳答案

这是因为浏览器会在动画放置到位之前转到 anchor 。有一些插件可以解决这类问题,或者您可以自己组装。

http://briangonzalez.org/arbitrary-anchor

简单实现的例子:

 jQuery.fn.anchorAnimate = function(settings) {

settings = jQuery.extend({
speed : 1100
}, settings);

return this.each(function(){
var caller = this
$(caller).click(function (event) {
event.preventDefault()
var locationHref = window.location.href
var elementClick = $(caller).attr("href")
var destination = $(elementClick).offset().top;

$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, settings.speed, function() {
window.location.hash = elementClick
});
return false;
})
})
}

关于javascript - jQuery 动画在 anchor 标记或 anchor 标记子项中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18904482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com