我的脚本不在wordpress静态站点中工作

时间:2016-07-07 20:32:26

标签: javascript php jquery wordpress

我在wordpress网站上工作,我在前面/主页上使用静态页面。我想使用视差滚动,但我不能让我的脚本加载和工作。

我在标题中将其链接为:

<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/scroll.js"></script>

这是我的滚动脚本:

(function($) {
    $.fn.parallax = function(options) {
        var windowHeight = $(window).height();
        // Establish default settings
        var settings = $.extend({
            speed: 0.15
        }, options);

        // Iterate over each object in collection
        return this.each( function() {

        // Save a reference to the element
        var $this = $(this);

            // Set up Scroll Handler
            $(document).scroll(function(){
                var scrollTop = $(window).scrollTop();
                var offset = $this.offset().top;
                var height = $this.outerHeight();

                // Check if above or below viewport
                if (offset + height <= scrollTop || offset >= scrollTop + windowHeight) {
                return;
                }

                var yBgPosition = Math.round((offset - scrollTop) * settings.speed);

                // Apply the Y Background Position to Set the Parallax Effect
                $this.css('background-position', 'center ' + yBgPosition + 'px'); 
            });
        });
    }
}(jQuery));

$('.parallax-section-1').parallax({
speed : 0.15
});

我发现了一些文章,我必须使用functions.php和enque脚本,但我从来没有这样做过,所以我有点迷失,所以任何帮助都会受到高度赞赏。

1 个答案:

答案 0 :(得分:0)

首先,让我们加载脚本&#34; WordPress Way&#34;。这实际上有助于简化故障排除。

为此,请修改主题的functions.php文件。

在该文件中,添加此PHP代码。确保它在<?php开始/结束标记之间。

通常,我建议将其添加到文件的 end ,但如果您的文件包含此?> - 您添加的代码是之前的 / em> ?>

add_action('enqueue_scripts', 'my_custom_script');

function my_custom_script() {
    // Be sure jQuery is loading
    wp_enqueue_script('jquery');
    // Load your script
    wp_enqueue_script('my-parallax-script', get_template_directory_uri() . '/js/scroll.js', array('jquery'), FALSE, TRUE);
}

现在 - 一旦你这样做,你将需要确保你的脚本实际上正在加载。要执行此操作,请访问该页面,然后在浏览器中执行查看源。当您查看源代码时,请搜索&#34; scroll.js&#34;的代码。 - 如果你找到了,那很好。单击URL(或将其复制/粘贴到浏览器窗口中)并确保脚本引用了正确的位置。如果没有,您需要确保将脚本移动到正确的位置,以便页面加载它。

下一步
您的脚本存在问题,在WordPress中无法正常工作。您正在引用带有$符号的jQuery,并且您似乎直接引用了一个元素,这意味着当脚本运行时该元素很可能不存在,这意味着它不会产生预期的效果。

相反,我们需要做两件事。因为WordPress在名为no conflict mode的内容中加载jQuery,所以您需要使用jQuery而不是$来引用它。您需要将代码放入document ready函数。

值得庆幸的是,为了方便起见,jQuery提供了一种方便的文档准备方式,可以在文档准备中公开$

// Shorthand version of "No-conflict-safe" document ready
jQuery(function($) {
    // Inside here, we can use $ instead of jQuery
    $('.parallax-section-1').parallax({
        speed : 0.15
    });
});

如果在所有这些之后仍然无效,那么您需要在浏览器中打开控制台,并查找任何javascript错误。它们将帮助您识别正在发生的事情,这是解决问题的第一步。