我有一个页面,其中一个滚动条包含从数据库动态生成的带有div的表行。每个表行就像一个链接,有点像你在视频播放器旁边看到的YouTube播放列表。
当用户访问页面时,他们所在的选项应该会转到滚动div的顶部。这个功能正在工作。问题是,这有点太过分了。比如他们的选项高了10像素。因此,页面被访问,url被用来识别选择了哪个选项,然后将该选项滚动到滚动div的顶部。注意:这不是窗口的滚动条,这是一个带有滚动条的div。
我正在使用这段代码,使它移动选中的选项到div的顶部:
var pathArray = window.location.pathname.split( '/' );
var el = document.getElementById(pathArray[5]);
el.scrollIntoView(true);
它将它移动到div的顶部,但大约10个像素太高了。
有人知道怎么解决吗?
我的主要想法是在我们想要滚动到的视图上方创建一个tempDiv。它在我的项目中工作得很好,没有滞后。
scrollToView = (element, offset) => {
var rect = element.getBoundingClientRect();
var targetY = rect.y + window.scrollY - offset;
var tempDiv;
tempDiv = document.getElementById("tempDiv");
if (tempDiv) {
tempDiv.style.top = targetY + "px";
} else {
tempDiv = document.createElement('div');
tempDiv.id = "tempDiv";
tempDiv.style.background = "#F00";
tempDiv.style.width = "10px";
tempDiv.style.height = "10px";
tempDiv.style.position = "absolute";
tempDiv.style.top = targetY + "px";
document.body.appendChild(tempDiv);
}
tempDiv.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
示例使用
onContactUsClick = () => {
this.scrollToView(document.getElementById("contact-us"), 48);
}
希望能有所帮助
解决方案,如果你是使用离子电容器,角材料,并需要支持iOS 11。
document.activeElement.parentElement.parentElement.scrollIntoView({block: 'center', behavior: 'smooth'});
关键是滚动到父节点的父节点,也就是输入的包装器。这个包装器包含输入的标签,该标签现在不再被切断。
如果你只需要支持iOS 14,“block”中心参数实际上是有效的,所以这是足够的:
document.activeElement.scrollIntoView({block: 'center', behavior: 'smooth'});
我的主要想法是在我们想要滚动到的视图上方创建一个tempDiv。它在我的项目中工作得很好,没有滞后。
scrollToView = (element, offset) => {
var rect = element.getBoundingClientRect();
var targetY = rect.y + window.scrollY - offset;
var tempDiv;
tempDiv = document.getElementById("tempDiv");
if (tempDiv) {
tempDiv.style.top = targetY + "px";
} else {
tempDiv = document.createElement('div');
tempDiv.id = "tempDiv";
tempDiv.style.background = "#F00";
tempDiv.style.width = "10px";
tempDiv.style.height = "10px";
tempDiv.style.position = "absolute";
tempDiv.style.top = targetY + "px";
document.body.appendChild(tempDiv);
}
tempDiv.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
示例使用
onContactUsClick = () => {
this.scrollToView(document.getElementById("contact-us"), 48);
}
希望能有所帮助