简体   繁体   中英

Custom cursor effect on Wordpress Theme

I am trying to add a custom cursor effect similar to below that is in Javascript to a Wordpress theme I am working on. I am new to creating my own theme and I am not sure where to apply the code. Should it go in functions.php or should I first create a sort of custom_script.js file and add the code in there?

Not sure which direction I should go into so any help would be appreciated.

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

The most typical and correct way to execute JavaScript code is to put it into *.js file, then register this file as a part of your theme and then call it in any template you need. Technically:

  1. Create a custom-cursor.js file in your theme and put your code there. (The js folder is usually a nice place to keep javascript files, so we assume your realtive path is js/custom-cursor.js ).
  2. Open your functions.php and register your script:
// 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. Optional) If you need to load the script only in a special template, you neead to call wp_enqueue_style( 'custom-cursor' ); right from its body. For example, you can open single.php and put this code there (before get_header() , this is important):

// 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();

Summary:

The basics: "Using_Javascript" (Codex)

Reference: wp_register_script()

Reference: wp_enqueue_script()

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM