滚动到一个ID减去一些像素



我已经有了下面的代码,并且在页面加载时可以很好地向下滚动到ID('expressRate'(。但随着需求的变化,页面应该向下滚动到div ID"expressRate"上方50像素的位置。如有任何帮助,我们将不胜感激。

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

滚动到标签'expressRate'后,请尝试此javascript代码

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.com/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];
}
}

最新更新