【问题标题】:How to phrase a jquery scroll function to work on one page but no other pages in a Wordpress website如何在 Wordpress 网站中使用 jquery 滚动功能在一个页面上工作但在其他页面上工作
【发布时间】:2014-09-05 10:19:52
【问题描述】:

在一个 wordpress 网站中,我将 current-menu-item 类删除到一个长滚动页面,并在顶部部分高于某个高度时将其添加回来。这很好用,但是在任何其他页面上滚动都会导致 addClass 返回到第一页导航以及当前(可见)页面。该网站可以在http://apurch.jvonhausen.com查看。我尝试添加 if is_page('home'),但这并不能区分这适用于哪个页面:

   $('#menu-item-15').removeClass('current-menu-item current_page_item');

    $(window).scroll(function() {
        var navitem = $('#menu-item-15');
        var currentPosition = $(this).scrollTop();
        var sliderheight = $('.home_slider').height();
        navitem.removeClass('current-menu-item current_page_item').each(function() {
          var top = $(this).offset().top,
          bottom = top + $(this).height();
          if (currentPosition >= top && currentPosition <= bottom) {
            $(navitem).addClass('current-menu-item current_page_item');
          }
          if (currentPosition < sliderheight || !($('.home'))) {
            $(navitem).removeClass('current-menu-item current_page_item');
          }
      });
    });

【问题讨论】:

    标签: javascript jquery html css wordpress


    【解决方案1】:

    您可以使用hasClass 来检查body 元素是否具有home 类,如果有,则仅应用代码。 WordPress 在正文中添加了有用的类,例如主页中的home 类。

    if($("body").hasClass("home")) {
        $('#menu-item-15').removeClass('current-menu-item current_page_item');
    
        $(window).scroll(function() {
            var navitem = $('#menu-item-15');
            var currentPosition = $(this).scrollTop();
            var sliderheight = $('.home_slider').height();
            navitem.removeClass('current-menu-item current_page_item').each(function() {
              var top = $(this).offset().top,
              bottom = top + $(this).height();
              if (currentPosition >= top && currentPosition <= bottom) {
                $(navitem).addClass('current-menu-item current_page_item');
              }
              if (currentPosition < sliderheight || !($('.home'))) {
                $(navitem).removeClass('current-menu-item current_page_item');
              }
          });
        });
    }
    

    或者,您可以使用is_home() 在排队或打印脚本标记之前检查您是否在主页上。

    【讨论】:

    • 非常感谢。像魅力一样工作!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2012-02-16
    • 1970-01-01
    • 2014-07-22
    • 2012-02-07
    相关资源
    最近更新 更多