【问题标题】:how to apply smooth scrolling using Gutenberg如何使用 Gutenberg 应用平滑滚动
【发布时间】:2021-06-12 09:55:08
【问题描述】:

我有一个包含如下链接的菜单

https://examples.com/#about-us
https://examples.com/#our-team
https://examples.com/#testimony
https://examples.com/#career
https://examples.com/#contact-us

我有一个单页应用,想在那里应用平滑滚动。

我用谷歌搜索了一下,found

generate_smooth_scroll_elements让你启动流畅 在其他元素类上滚动,而不仅仅是带有 smooth-scroll 班级。

使用以下 PHP sn-p 将平滑滚动应用于所有哈希 链接:

add_filter( 'generate_smooth_scroll_elements', function( $elements ) {
  $elements[] = 'a[href*="#"]';
  
  return $elements;
} );

我只想平滑滚动到特定的类。

如何使用古腾堡块编辑器应用特定的类并在那里平滑滚动。

【问题讨论】:

  • 您在询问 Gutenberg(它是基于 js 的)并提供了一个 PHP-example ),这是行不通的。
  • 可以在 Javascript 的帮助下完成,很多这样的问题:stackoverflow.com/questions/17722497/…
  • 我实际上是 wordpress 的新手,所以不确定可以做什么或不可以做什么。如果我需要 html、css 或 javascript 也可以。
  • 如果您需要 html、js、css 或 php 方面的帮助,您不是 Wordpress 新手,您只是开发新手。我敢肯定 youtube 上有很多有用的东西。
  • 查看这篇文章,例如webdesign.tutsplus.com/tutorials/…

标签: wordpress


【解决方案1】:

在这里,试试这个小插件。但是,您应该自己指定平滑滚动链接,方法是向它们添加“平滑滚动”类,如下所示:<a href="#test" class="smooth_scroll" data-type="internal" data-id="#test">Smooth Scroll Link</a>

<?php
/**
 * Plugin Name: Native Smooth Scroll
 * Plugin URI:
 * Description: Simple plugin for smooth scroll to anchors using native JS scrollIntoView() method.
 * Author: Paul Fedorov
 * Author URI: https://github.com/acerus
 * Requires at least: 5.0
 * Tested up to: 5.4
 * Version: 1.0
 * Stable tag: 1.0
 *
 * Text Domain: native-smooth-scroll
 * Domain Path: /languages/
 *
 */

function enqueue_scripts() { ?>

  <script>

  const smooth_links = document.querySelectorAll('a.smooth_scroll[href^="#"]');

  for (const link of smooth_links) {
    link.addEventListener("click", clickHandler);
  }

  function clickHandler (event) {
    event.preventDefault();
    const href = this.getAttribute("href");

    document.querySelector(href).scrollIntoView({
      behavior: "smooth"
    });
  }

  </script>

<?php }

add_action('wp_footer', 'enqueue_scripts');

我假设您使用 generatepress 主题,因此最好使用插件添加任何自定义功能,并且不要更改主题本身,这样您就不会在更新主题后丢失任何内容。

【讨论】:

  • data-type="internal" data-id="#test"的意义是什么?
  • 我刚刚从古腾堡复制了那部分,以供参考。这就是它向元素添加锚点的方式。
猜你喜欢
  • 1970-01-01
  • 2017-05-15
  • 2018-04-03
  • 2011-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多