我在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并加入脚本的文章,但我之前从未这样做过,因此我有点迷失了,所以我们将不胜感激。

最佳答案

首先,让我们以“ WordPress方式”加载脚本。这实际上将有助于简化故障排除。

为此,请编辑主题的functions.php文件。

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

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

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


现在-完成此操作后,您将要确保脚本实际上正在加载。为此,请访问页面,然后在浏览器中执行“查看源”。当您查看源代码时,请搜索“ scroll.js”的代码-如果找到它,那就太好了。单击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错误。他们将帮助您确定正在发生的事情,这是解决问题的第一步。

关于javascript - 我的脚本无法在Wordpress静态站点中运行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38254757/

10-12 00:22
查看更多