0

我花了一天的大部分时间来跟踪我在使用 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 事件处理程序调用放在 <a> 标记中还是其中的 <div> 中,动画都不起作用。另一方面,如果我完全删除 <a> 元素标记,则动画在 <div> 元素上按预期工作。

有谁知道为什么会这样?

这个问题几乎没有实际意义,因为我可以轻松地使用工作页面中的 <div> 元素来完成我也可以使用 <a> 元素来完成的工作。在工作代码(更复杂)中,我在锚元素上使用 event.preventDefault(),以便链接和其他操作由显式事件处理程序驱动,这也可以从 <div> 完成。我相信我什至可以在将鼠标悬停在 <div> 上时更改指针图标,以便它在这方面也能模仿真正的锚点。

4

1 回答 1

0

这是因为浏览器会在动画到位之前到达锚点。有一些插件可以解决这些问题,或者你可以自己组装。

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;
        })
    })
}
于 2013-09-19T20:51:25.130 回答