【问题标题】:jQuery animation not working in anchor tags or anchor tag childrenjQuery 动画在锚标记或锚标记子项中不起作用
【发布时间】:2013-09-19 20:38:08
【问题描述】:

我花了一天的大部分时间来跟踪我在使用 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 事件处理程序调用放在 标记还是其中的

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

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

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

标签: javascript jquery css html


【解决方案1】:

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

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

【讨论】:

  • Stefano D 似乎成功了。添加代码以禁用锚标记的默认事件处理程序允许单击落入封闭的 div 并且代码有效。虽然我已经在生产页面上处理了这个问题,但显然我需要考虑到这一点来重新审视代码。
猜你喜欢
  • 1970-01-01
  • 2013-06-12
  • 2013-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-15
相关资源
最近更新 更多