如何在 WordPress 网站上的 PHP 脚本中运行 JavaScript 类?

huangapple go评论77阅读模式
英文:

How to run javascript class on php script on a wordpress website?

问题

我正在使用WordPress开发网站,并在调用包含根据某些事件描述动画的代码的JavaScript文件时遇到问题。

实际上,这个文件包含根据某些事件正确调用的函数。然而,这个文件包含一个类,这就是我遇到问题的地方,因为我无法访问这个类的构造函数和其方法。

这是一个.php文件的模板示例:

<?php
if(get_field('test'))
{ ?>
   
<section>

    <div class="overflow-h" id="parallaxContainer">
        <?php if ( wp_is_mobile() ) {?>
            <img class="full-img">
        <?php } else { ?>
            <img class="full-img" data-parallax="0.2" id="target">
        <?php } ?>
    </div>
</section>
   
<?php
}
?>

这是JavaScript文件(main.js)的一部分:

const scrollContainer = document.querySelector("main");

let isDown = false;
let startX;
let scrollLeft;

scrollContainer.addEventListener('mousedown', (e) => {
    isDown = true;
    startX = e.pageX - scrollContainer.offsetLeft;
    scrollLeft = scrollContainer.scrollLeft;
});

scrollContainer.addEventListener('mouseleave', () => {
    isDown = false;
});

scrollContainer.addEventListener('mouseup', () => {
    isDown = false;
});

scrollContainer.addEventListener('mousemove', (e) => {
    if (!isDown) return;
    e.preventDefault();
    const x = e.pageX - scrollContainer.offsetLeft;
    const walk = (x - startX) / 10;
    scrollContainer.scrollLeft = scrollLeft - walk;
});

// 无法访问类...
class Parallax {
    constructor(element) {
        this.element = element;
        this.onScroll = this.onScroll.bind(this);
        document.addEventListener('scroll', this.onScroll);
    }

    onScroll() {
        const middleScreenWidth = window.scrollX + window.innerWidth / 2;
    }

    bind() {
        return Array.from(document.querySelectorAll("[data-parallax]")).map(
            (element) => {
                return new Parallax(element);
            });
    }
}

这是调用JavaScript文件(main.js)的.php文件:我使用WordPress函数add_action调用我的JavaScript脚本:

function call_scripts() {
    wp_enqueue_style( 'call-style', get_stylesheet_uri(), array(), _S_VERSION );
    wp_enqueue_script( 'call-main', get_template_directory_uri() . '/js/main.js', array(), _S_VERSION, true );
}
add_action( 'wp_enqueue_scripts', 'call_scripts' );

感谢您的帮助。

英文:

I am developing a website using WordPress and I encounter a problem in the call of the javascript file that contains code that allows me to describe animations according to certain events.

Indeed this file contains functions that are called correctly according to certain events. However this file contains a class and this is where I encounter a problem because I can not access the constuctor of this class and its methods.

here is the template which is a .php file:

&lt;?php

        if(get_field(&#39;test&#39;))
        { ?&gt;
       
        &lt;section&gt;

            &lt;div class=&quot;overflow-h&quot; id=&quot;parallaxContainer&quot;&gt;
                &lt;?php if ( wp_is_mobile() ) {?&gt;
                    &lt;img class=&quot;full-img&quot;&gt;
                &lt;?php } else { ?&gt;
                    &lt;img class=&quot;full-img&quot; data-parallax=&quot;0.2&quot; ?&gt; id=&quot;target&quot;&gt;
                &lt;?php } ?&gt;
            &lt;/div&gt;
        &lt;/section&gt;
       
    &lt;?php
        }
    ?&gt;

here is the javascript file (mains.js):

const scrollContainer = document.querySelector(&quot;main&quot;);

let isDown = false;
let startX;
let scrollLeft;

scrollContainer.addEventListener(&#39;mousedown&#39;, (e) =&gt; {
    isDown = true;
    startX = e.pageX - scrollContainer.offsetLeft;
    scrollLeft = scrollContainer.scrollLeft;
});

scrollContainer.addEventListener(&#39;mouseleave&#39;, () =&gt; {
    isDown = false;
});

scrollContainer.addEventListener(&#39;mouseup&#39;, () =&gt; {
    isDown = false;
});

scrollContainer.addEventListener(&#39;mousemove&#39;, (e) =&gt; {
    if(!isDown) return;
    e.preventDefault();
    const x = e.pageX - scrollContainer.offsetLeft;
    const walk = (x - startX)/10;
    scrollContainer.scrollLeft = scrollLeft - walk;
});

//Can&#39;t access to the class...
class Parallax {
    constructor(element) {
        this.element = element;
        this.onScroll = this.onScroll.bind(this);
        document.addEventListener(&#39;scroll&#39;, this.onScroll)
    }

 
 onScroll() {
    const middleScreenWidth = window.scrollX + window.innerWidth / 2;
}


 bind() {
    return Array.from(document.querySelectorAll(&quot;[data-parallax]&quot;)).map(
        (element) =&gt; {
            return new Parallax(element);
        });
    }
}

this is the .php file that calls the javascript file (main.js): I call my js script thanks to the WordPress function 'add_action'

function call_scripts() {
    wp_enqueue_style( &#39;call-style&#39;, get_stylesheet_uri(), array(), _S_VERSION );
    wp_enqueue_script( &#39;call-main&#39;, get_template_directory_uri() . &#39;/js/main.js&#39;, array(), _S_VERSION, true );
}
add_action( &#39;wp_enqueue_scripts&#39;, &#39;call_scripts&#39; );

Thanks for help

答案1

得分: 1

bind逻辑移出class并放入一个单独的函数中。原因是你不希望Parallax实例能够创建更多实例,因为这不是它们的责任。

class Parallax {
  constructor(element) {
    this.element = element;
    document.addEventListener('scroll', this.onScroll);
  }

  onScroll = () => {
    const middleScreenWidth = window.scrollX + window.innerWidth / 2;
  }
}

创建一个新的函数,返回一个Parallax实例数组。这是工厂函数模式,有助于创建多个实例。

function createParallax() {
  return Array.from(document.querySelectorAll("[data-parallax]")).map(
    (element) => new Parallax(element)
  );
}

调用该函数并将Parallax实例存储在一个变量中。

const parallaxes = createParallax();

正如之前提到的:scroll事件监听器会对性能造成压力,因为它在每个像素上都被调用。如果你必须为10个元素执行这个操作,那么它必须在每个像素上进行10次新的计算。这会非常快速地变慢。

解决方法是使用一个单一的scroll事件监听器,将事件处理程序设置为被动事件监听器,并跟踪在视图中的元素,视图之外的元素不需要进行动画,从而提高性能。

英文:

Move the bind logic out of the class and put in a seperate function. The reason for this is that you don't want a Parallax instance to be able to create more instances as that is not their concern.

class Parallax {
  constructor(element) {
    this.element = element;
    document.addEventListener(&#39;scroll&#39;, this.onScroll)
  }

  onScroll = () =&gt; {
    const middleScreenWidth = window.scrollX + window.innerWidth / 2;
  }
}

Create a new function that returns an array of Parallax instances. This is factory function pattern, which can help in creating multiple instances.

function createParallax() {
  return Array.from(document.querySelectorAll(&quot;[data-parallax]&quot;)).map(
    (element) =&gt; new Parallax(element)
  );
}

Call the function and store the Parallax instances in a variable.

const parallaxes = createParallax();

Like mentioned earlier: the scroll event listener puts a strain on your performance as it is being called with every pixel. If you have to do that, for let's say 10 elements, then it has to do a new calculation 10 times every pixel. This becomes slow very fast.

The solution for this would be to use a single scroll event listener, make the event handler a passive event listener, and keep track of the elements that are in view, elements outside of view don't have to be animated, which saves performance.

huangapple
  • 本文由 发表于 2023年6月6日 02:03:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76408934.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定