如何禁用Divi主题锚点链接的滚动动画?
解决Divi主题锚点链接取消平滑滚动、实现即时跳转的方法
Divi主题默认通过et_pb_smooth_scroll函数实现锚点平滑滚动,直接修改主题核心文件(如scripts.js)会导致更新后失效,以下是无需修改主题核心文件的解决方案:
方法一:通过子主题加载自定义JS覆盖滚动行为
- 在你的Divi子主题目录下创建
js/custom-scroll.js文件,写入以下代码:
jQuery(document).ready(function($) { // 解绑Divi绑定的锚点点击事件 $('#nav-section a[href^="#"]').off('click.et_pb_smooth_scroll'); // 重新绑定点击事件,实现即时跳转 $('#nav-section a[href^="#"]').on('click', function(e) { e.preventDefault(); var targetHash = this.hash; var $target = $(targetHash); if ($target.length) { // 直接设置滚动位置,无动画 $('html, body').scrollTop($target.offset().top); // 更新URL哈希,避免浏览器历史记录异常 history.pushState(null, null, targetHash); } }); });
- 在子主题的
functions.php中添加代码,注册并加载这个自定义脚本:
function disable_divi_smooth_scroll() { // 确保在Divi的脚本之后加载 wp_enqueue_script( 'custom-scroll', get_stylesheet_directory_uri() . '/js/custom-scroll.js', array('jquery'), wp_get_theme()->get('Version'), true ); } add_action('wp_enqueue_scripts', 'disable_divi_smooth_scroll', 20);
方法二:直接修改Divi平滑滚动的动画时长
通过wp_add_inline_script在Divi核心脚本之后注入代码,覆盖et_pb_smooth_scroll函数的默认动画时长为0:
在子主题的functions.php中添加以下代码:
function override_divi_smooth_scroll_speed() { // 针对Divi的核心脚本句柄注入代码 wp_add_inline_script('divi-custom-script', ' jQuery(document).ready(function($) { // 重写et_pb_smooth_scroll函数,将动画时长设为0 window.et_pb_smooth_scroll = function(target, context, speed) { speed = 0; var $target = $(target); if ($target.length) { $(context).scrollTop($target.offset().top); if (history.pushState) { history.pushState(null, null, target); } else { window.location.hash = target; } } }; }); '); } add_action('wp_enqueue_scripts', 'override_divi_smooth_scroll_speed', 20);
问题说明
你之前的代码出现向上滚动问题,是因为没有解绑Divi原生的et_pb_smooth_scroll点击事件,导致自定义事件和原生事件冲突,同时scrollTop: $trget的写法错误,应该使用$trget.offset().top获取目标元素的顶部位置。优先使用子主题修改,避免主题更新后丢失自定义设置。
内容的提问来源于stack exchange,提问作者pseudojk
相关产品推荐
相关产品推荐

