最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Scroll to an ID minus some pixels - Stack Overflow

programmeradmin1浏览0评论

I have below code already and working well to scroll down to the ID ('expressRate') on page loading. But with change of requirement the page should scroll down to a point 50 pixels above the div ID 'expressRate'. Any help would be appreciated.

 $location.hash('expressRate');
 $anchorScroll();

I have below code already and working well to scroll down to the ID ('expressRate') on page loading. But with change of requirement the page should scroll down to a point 50 pixels above the div ID 'expressRate'. Any help would be appreciated.

 $location.hash('expressRate');
 $anchorScroll();
Share Improve this question asked Dec 4, 2018 at 15:04 YespieYespie 1922 gold badges3 silver badges14 bronze badges 1
  • Get the vertical api.jquery./offset , subtract 50, and api.jquery./scrollTop/#scrollTop2 the window down to it. – Taplar Commented Dec 4, 2018 at 15:15
Add a ment  | 

3 Answers 3

Reset to default 3

try this javascript code after you scroll to the tag 'expressRate'

window.location('#expressRate');
window.scrollBy(0,-50);

//get the element
var $expressRate = $('#expressRate');
//get the vertical distance of the element from the top of the page
var verticalPositionOfElement = $expressRate.offset().top;

//added a timeout just so you could see the start and then the
//adjustment
setTimeout(function () {
  //scroll the window down the element distance, minus whatever
  $(window).scrollTop(verticalPositionOfElement - 50);
}, 1000);
html, body {
  min-height: 5000px;
}

#expressRate {
  min-height: 200px;
  margin-top: 1000px;
  background-color: red;
}
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="expressRate">

window.scroll(0,findPos(document.getElementById("expressRate")) - 50);

    function findPos(obj) {
        var curtop = 0;
        if (obj.offsetParent) {
            do {
                curtop += obj.offsetTop;
            } while (obj = obj.offsetParent);
        return [curtop];
        }
    }
发布评论

评论列表(0)

  1. 暂无评论