javascript - 如何在没有滚动行为的情况下转到特定部分/没有滚动行为的 scrollIntoView() 的任何替代方法?
问题描述
我正在尝试创建到特定部分的页面重定向,即我想转到页面上的特定锚 div 而没有滚动行为。但是,我在 URL 中有一个用于分页的查询字符串,因此 #id 方法对我来说失败了。我尝试了“scrollIntoView()”,但它包含页面滚动行为,这是不受欢迎的。请问是否有任何替代解决方案来解决这个问题?
我在前端使用 Vue,在后端使用 Codeigniter。这是我的代码:
mounted() {
// anchorPageToProductList
if (this.isOnQuery) {
console.log('isOnQuery');
this.scrollToProductList();
} else {
console.log('isNotOnQuery');
}
},
methods: {
scrollToProductList(){
window.addEventListener('DOMContentLoaded', () => {
// scroll animation
document.getElementById('product-list-anchor').scrollIntoView(true);
});
},
我的 URL 案例示例:
http://www.example.com/Product/list?search=&sort=3&type=-1&event%5B%5D=11&pagination=1
谢谢!!
解决方案
我试图取消设置滚动行为,允许页面跳转到所需的部分,然后设置回平滑滚动行为。所以它现在可以在没有滚动行为的情况下工作。感谢所有的评论:)
我的代码:
scrollToProductList(){
window.addEventListener('DOMContentLoaded', () => {
// select the whole html & disable smooth-scroll behavior in css
let htmlElement = document.querySelector('html');
htmlElement.style.scrollBehavior = 'auto';
// go to the anchor point
document.getElementById('product-list-anchor').scrollIntoView(true);
// enable smooth-scroll behavior again
htmlElement.style.scrollBehavior = 'smooth';
});
}
推荐阅读
- linux - 用php从虚拟机(Linux)获取物理机信息
- java - 为什么同一个静态字段在dalvik中有两个不同的id?
- url - Python suds 客户端 urlopen 超时错误?
- javascript - 如何将 Firestore 添加到我的 Javascript 代码中?
- reactjs - 带有 React 和 Redux 的模态窗口
- r - 具有线性和 log10 轴的表达式图
- ruby - 按帖子数量对 Jekyll 标签进行排序
- javascript - Django 动态添加表单 - 'NoneType' 和 'int' 的实例之间不支持'<'
- html - Angular EventEmitter 获取数据
- angular - 如何在 Angular 中以编程方式设置 ngModel 绑定?