使用WordPress菜单设置平滑滚动

时间:2015-05-12 13:35:56

标签: javascript php jquery wordpress

我正在尝试使用WordPress菜单超链接实现平滑滚动的几个问题

如果我使用一个简单的超链接并为其分配一个类page-scroll,则平滑滚动工作完全正常但是在生成wordpress菜单时,我正在尝试将类page-scroll指定给<a>标记但这不起作用,所以我想尽快通过JavaScript将page-scroll类分配给菜单{/ 1}}。

将鼠标悬停在hover内的<a>,但平滑滚动似乎不适用。

这是我用于平滑滚动的JS

#menu-main-menu

这是创建的wordpress菜单html

$('.menu-item').hover(function(){
        $('#menu-main-menu').children().children('a').addClass('page-scroll');
    });

    $('a.page-scroll').click(function() {
        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
          var target = $(this.hash);
          target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
          if (target.length) {
            $('html,body').animate({
              scrollTop: target.offset().top - 40
            }, 900);
            return false;
          }
        }
      });

我真的很感激你的帮助。

2 个答案:

答案 0 :(得分:0)

您是否只能在加载页面后立即绑定所有菜单项?像这样:

jQuery(document).ready(function($) {
  $('.menu-item > a').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top - 40
        }, 900);
        return false;
      }
    }
  });
});

[编辑]通过,我只是在我的答案中复制了你的代码,但我觉得它有一些错误,你可能想在加载页面时检查浏览器的控制台并确保所有的变量和函数确实存在

[edit2]如果你需要绑定所有菜单项以及<a>类的page-scroll标签,这应该有效:

jQuery(document).ready(function($) {
  $('.menu-item > a, a.page-scroll').click(function() {
    // your scrolling function
  });
});

您还可以绑定所有<a>代码(我不建议这样做):

jQuery(document).ready(function($) {
  $('a').click(function() {
    // your scrolling function
  });
});

答案 1 :(得分:0)

此处您正在悬停时向锚点添加类,因此请尝试在加载时为您的锚点添加类,或者在您的dom准备就绪后执行此操作

$(document).ready(function(){
   //add class to your anchor
     $('.menu-item > a').addClass('page-scroll');
});

希望这将解决您的问题