【问题标题】:.animate() not working on Wordpress site.animate() 在 Wordpress 网站上不起作用
【发布时间】:2014-06-17 11:06:58
【问题描述】:

我正在尝试对与页面上的 hashbang 链接关联的滚动使用动画效果。

当我在常规网站上使用它时,它可以完美运行。

当我尝试在 wordpress 网站上使用它时,它没有动画,它只是跳转到 DIV 而不是滚动。

jQ 代码(尝试将其放在头部、正文和页脚中(没有区别):

<script type="text/javascript">
jQuery.noConflict();
jQuery(document).ready(function(){
$('a[href^="#"]').on('click',function (e) {
    e.preventDefault();

    var target = this.hash,
    $target = $(target);

    $('html, body').stop().animate({
        'scrollTop': $target.offset().top
    }, 900, 'swing', function () {
        window.location.hash = target;
    });
});
});
</script>

如果出现问题,这是我当前的 JQuery 版本?

jquery.js?ver=1.11.0

jquery-migrate.min.js?ver=1.2.1

这可能是 wordpress 对脚本进行排队的顺序吗?

任何想法,因为我在这里拉头发!

【问题讨论】:

  • 链接到您的网站以查看问题?
  • 在您完成jQuery.noConflict(); 之后,您将无法再使用$。查看JavaScript error console 并告诉您在那里看到的错误以及它们指向的行。
  • Juhana,我最初并没有使用 noConflict,我只是作为最后的手段尝试了它,因为它没有以其他方式工作。不过谢谢,我会检查一下。

标签: javascript jquery wordpress scroll jquery-animate


【解决方案1】:

尝试使用 wrap (function($){ //your content })(jQuery);

(function($){
    $(document).ready(function(){
        $('a[href^="#"]').on('click',function (e) {
            e.preventDefault();
            var target = this.hash,
            $target = $(target);

            $('html, body').stop().animate({
                'scrollTop': $target.offset().top
            }, 900, 'swing', function(){
                window.location.hash = target;
            });
        });
    });
})(jQuery);

【讨论】:

  • 谢谢乔佛里,这很好用!我会尽快将其作为正确答案进行检查。
【解决方案2】:

改成这样:

<script type="text/javascript">
    jQuery(document).ready(function($){ // pass $ as an arg here

您需要在就绪回调中将$ 作为参数传递,并且您不需要jQuery.noConflict();,因此请将其删除。


因为 wordpress 使用 jQuery 而不是 $,所以这不会与使用 $ 作为别名的其他库发生冲突,所以你可以做两件事

  1. 按照上面的建议做,或者
  2. 用 jQuery 替换每次出现的 $

【讨论】:

  • 啊,好吧,我不知道。非常有用的信息,谢谢 Jai ;)
  • @Grant 很高兴这在某种程度上有所帮助。
猜你喜欢
  • 2021-10-26
  • 2015-10-11
  • 2019-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多