如果滚动没有过渡效果请增加以下样式
html,body{
scroll-behavior:smooth;
}
滚动dom节点的所在位置
/* 获取当前dom节点到窗口的位置 */
console.log(
document.querySelector("#searchScroll").getBoundingClientRect().top
);
/* 跳转到此dom节点 这个默认滚动到顶部 不可以设置间距*/
document.querySelector('#searchScroll').scrollIntoView({
behavior: 'smooth',
block: 'center',
})
/* 跳转到此dom节点 这个可以设置距离顶部的值 上面的也有behavior平滑滚动的参数*/
window.scrollTo({
top: this.$refs["item50"][0].getBoundingClientRect().top - 30,
behavior: "smooth",
});
缓慢滚动置顶
var ding = document.getElementById('ding');
ding.addEventListener('click', function () {
var timer = setInterval(function () {
var left = window.pageYOffset;
var step = Math.ceil((left - 0) / 10);
window.scroll(0, left - step);
if (left == 0) {
clearInterval(timer);
}
}, 30)
})
获取当前页面的滚动位置
const getScrollPosition = (el = window) => ({
x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop
});
// 事例
getScrollPosition(); // {x: 0, y: 200}
如何平滑滚动到页面顶部
const scrollToTop = () => {
const c = document.documentElement.scrollTop || document.body.scrollTop;
if (c > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, c - c / 8);
}
}
// 事例
scrollToTop()
检查指定的元素在视口中是否可见
const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
const { top, left, bottom, right } = el.getBoundingClientRect();
const { innerHeight, innerWidth } = window;
return partiallyVisible
? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) &&
((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
: top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
};
// 事例
elementIsVisibleInViewport(el); // 需要左右可见
elementIsVisibleInViewport(el, true); // 需要全屏(上下左右)可以见
获取自适应的高度
getAutoheight(dom, bottomMargin) {
let screenHeight = window.innerHeight || document.body.clientHeight
let _dom = document.querySelector(dom)
if (!_dom) return '250'
let { top } = _dom && _dom.getBoundingClientRect()
// 这样算出来得高度就是整个屏幕 减掉top的长度 但最后为了不贴底部 就会减掉自定义的长度 也就是bottomMargin 这样可达到自适应长度
return screenHeight - Math.ceil(top) - bottomMargin
}
getAutoheight('.getBoundingClientRect', 70)