首页 > 解决方案 > Wordpress 主题上的自定义光标效果

问题描述

我正在尝试将类似于下面的自定义光标效果添加到我正在处理Javascript的主题中。Wordpress我是创建自己的主题的新手,我不确定在哪里应用代码。它应该进入functions.php还是我应该首先创建一个custom_script.js文件并在其中添加代码?

不知道我应该进入哪个方向,所以任何帮助将不胜感激。

(function fairyDustCursor() {

  var possibleColors = ["#D61C59", "#E7D84B", "#1B8798"]
  var width = window.innerWidth;
  var height = window.innerHeight;
  var cursor = {
    x: width / 2,
    y: width / 2
  };
  var particles = [];

  function init() {
    bindEvents();
    loop();
  }

  // Bind events that are needed
  function bindEvents() {
    document.addEventListener('mousemove', onMouseMove);
    document.addEventListener('touchmove', onTouchMove);
    document.addEventListener('touchstart', onTouchMove);

    window.addEventListener('resize', onWindowResize);
  }

  function onWindowResize(e) {
    width = window.innerWidth;
    height = window.innerHeight;
  }

  function onTouchMove(e) {
    if (e.touches.length > 0) {
      for (var i = 0; i < e.touches.length; i++) {
        addParticle(e.touches[i].clientX, e.touches[i].clientY, possibleColors[Math.floor(Math.random() * possibleColors.length)]);
      }
    }
  }

  function onMouseMove(e) {
    cursor.x = e.clientX;
    cursor.y = e.clientY;

    addParticle(cursor.x, cursor.y, possibleColors[Math.floor(Math.random() * possibleColors.length)]);
  }

  function addParticle(x, y, color) {
    var particle = new Particle();
    particle.init(x, y, color);
    particles.push(particle);
  }

  function updateParticles() {

    // Updated
    for (var i = 0; i < particles.length; i++) {
      particles[i].update();
    }

    // Remove dead particles
    for (var i = particles.length - 1; i >= 0; i--) {
      if (particles[i].lifeSpan < 0) {
        particles[i].die();
        particles.splice(i, 1);
      }
    }

  }

  function loop() {
    requestAnimationFrame(loop);
    updateParticles();
  }

  /**
   * Particles
   */

  function Particle() {

    this.character = "*";
    this.lifeSpan = 120; //ms
    this.initialStyles = {
      "position": "absolute",
      "display": "block",
      "pointerEvents": "none",
      "z-index": "10000000",
      "fontSize": "16px",
      "will-change": "transform"
    };

    // Init, and set properties
    this.init = function(x, y, color) {

      this.velocity = {
        x: (Math.random() < 0.5 ? -1 : 1) * (Math.random() / 2),
        y: 1
      };

      this.position = {
        x: x - 10,
        y: y - 20
      };
      this.initialStyles.color = color;
      console.log(color);

      this.element = document.createElement('span');
      this.element.innerHTML = this.character;
      applyProperties(this.element, this.initialStyles);
      this.update();

      document.body.appendChild(this.element);
    };

    this.update = function() {
      this.position.x += this.velocity.x;
      this.position.y += this.velocity.y;
      this.lifeSpan--;

      this.element.style.transform = "translate3d(" + this.position.x + "px," + this.position.y + "px,0) scale(" + (this.lifeSpan / 120) + ")";
    }

    this.die = function() {
      this.element.parentNode.removeChild(this.element);
    }

  }

  /**
   * Utils
   */

  // Applies css `properties` to an element.
  function applyProperties(target, properties) {
    for (var key in properties) {
      target.style[key] = properties[key];
    }
  }

  init();
})();

标签: javascriptwordpress

解决方案


执行 JavaScript 代码的最典型和正确的方法是将其放入*.js文件中,然后将此文件注册为主题的一部分,然后在您需要的任何模板中调用它。技术上:

  1. 在您的主题中创建一个custom-cursor.js文件并将您的代码放在那里。(该 js文件夹通常是保存 javascript 文件的好地方,因此我们假设您的实际路径是js/custom-cursor.js)。
  2. 打开您的functions.php并注册您的脚本:
// This function will register your frontend scripts
// to let WordPress handle their loading

function rhonda_frontend_scripts() {

    // We shouldn't call frontend scripts on admin side, so...
    if ( ! is_admin() ) {

        // Ok, let's register a script
        wp_register_script(
            // Set a script name (unique handler) to call it later
            'custom-cursor',
            // Specify a path to your javascipt file
            get_template_directory_uri() . '/js/theme.min.js',
            // Leave dependencies array blank (your code doesn't require any other scripts)
            array(),
            // Don't specify a version (you can read about this later)
            false,
            // Yes, call this script in the footer 
            // after the main content (for performance reasons)
            true
        );

        // After the registration, you are able to load the script 
        // from any template using it's handler 

        // And since your cursor should be probably loaded on every page, 
        // you can load it just once right here in functions.php instead.
        wp_enqueue_style( 'custom-cursor' );

        // Ok, now you can add one more script if you wish.

    }
}

// But don't forget that we need to call our registration function right in time, 
// before the template is displayed, so we should use a hook.
// There is a special hook for this purpose: 'wp_enqueue_scripts'

add_action( 'wp_enqueue_scripts', 'rhonda_frontend_scripts' );

// Done :)

(3. 可选) 如果只需要在特殊模板中加载脚本,则需要wp_enqueue_style( 'custom-cursor' );从其正文中直接调用。例如,您可以打开single.php并将这段代码放在那里(之前get_header(),这很重要):

// This function will inject your scripts in the header/footer 
// of any page, which uses this .php template file
function rhonda_single_template_scripts() {
    wp_enqueue_script( 'custom-cursor' );
}

// Don't forget to call it via special hook 'wp_enqueue_scripts'.
add_action( 'wp_enqueue_scripts', 'rhonda_single_template_scripts' );

// ...

// get_header();

概括:

基础知识:“Using_Javascript”(法典)

参考:wp_register_script()

参考:wp_enqueue_script()

希望这可以帮助。


推荐阅读