首页 > 解决方案 > Scrolltop 偏移量最高的问题

问题描述

我使用下面提到的代码滚动到一个 div。我scrollTop: $(target).offset().top-250在移动视图中应用,以便该部分将显示在标题高度下方,但它似乎不起作用。

$('#portfolioNavbar ul li a[href*=#]').bind('click', function(e) {
  e.preventDefault();
  var target = $(this).attr("href");

  $('html, body').stop().animate({
    scrollTop: $(target).offset().top - 250
  }, 600, function() {
    location.hash = target; //attach the hash (#jumptarget) to the pageurl
  });

  return false;
});

标签: jqueryhtml

解决方案


下面的脚本节省了我的时间。该脚本可能对其他人有用。

$('#portfolioNavbar ul li a').click(function() {
     var tghsh = $(this).attr('href').substring(1);
     var headerHeight = $('.portfolioi_left').outerHeight();
     var winwid = $(window).width();
     var doffset = $('#'+tghsh).offset().top-20;
     var doffset1 = $('#'+tghsh).offset().top-280;
     if(winwid <= 991) {
         doffset1 -= headerHeight;
     $('html, body').animate({scrollTop:doffset1},700);
     return false;
     }
     $('html, body').animate({scrollTop:doffset},700);
     return false;
});

如果想让菜单在滚动到 div 时处于活动状态。你能用这个脚本吗

$(document).ready(function() {
$('#portfolioNavbar ul li a').click(function() {
     $(document).off("scroll");

    $('#portfolioNavbar ul li a').each(function () {
        $(this).removeClass('active');
    })
    $(this).addClass('active');
     var tghsh = $(this).attr('href').substring(1);
     var headerHeight = $('.portfolioi_left').outerHeight();
     var winwid = $(window).width();
     var doffset = $('#'+tghsh).offset().top-20;
     var doffset1 = $('#'+tghsh).offset().top-280;
     if(winwid <= 991) {
         doffset1 -= headerHeight;
     $('html, body').animate({scrollTop:doffset1},700);
     return false;
     }
     $('html, body').animate({scrollTop:doffset},700);
     return false;
});
});

function onScroll(event){
    var scrollPos = $(document).scrollTop();
    $('#portfolioNavbar ul li a').each(function () {
    var currLink = $(this);
    var refElement = $(currLink.attr("href"));
    if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
        $('#portfolioNavbar ul li a').removeClass("active");
        currLink.addClass("active");
    }
    else{
        currLink.removeClass("active");
    }
});
};

推荐阅读