j查询动画在锚标记或锚标记子项中不起作用

jQuery animation not working in anchor tags or anchor tag children

本文关键字:不起作用 动画 查询      更新时间:2023-09-26

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

<!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 事件处理程序调用放在 标记中还是放在其中的

有谁知道为什么会这样?

这个问题几乎没有意义,因为我可以轻松地在工作页面中使用

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

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

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;
        })
    })
}