【问题标题】:Is there a way to preserve scrollIntoView behaviour in a PDF?有没有办法在 PDF 中保留 scrollIntoView 行为?
【发布时间】:2019-09-03 09:07:01
【问题描述】:
我在网站上有一个页面,当点击某些单词时,它使用scrollIntoView 跳转到页面的其他部分。
当将页面打印为 PDF 时(使用 Chrome,通过浏览器打印并将目标更改为 PDF),scrollIntoView 行为显然会丢失。
但是我以前看过带有目录的 PDF,所以我知道可以通过文档进行链接,但是在使用 Chrome 的网页到 PDF 功能时,有什么方法可以实现该链接?
【问题讨论】:
标签:
javascript
google-chrome
pdf
browser
【解决方案1】:
您可以在链接上使用href="#other-elements-id" 以使该链接滚动到它(linking to another section on MDN)。如果您在 Chrome 中将页面打印为 PDF,这仍然有效。
如果您添加事件侦听器,您可以阻止这种默认行为,并且在您使用浏览器而不是 PDF 时仍然使用 scrollIntoView。
var link = document.getElementById('link');
var section = document.getElementById('section');
link.addEventListener('click', function(e) {
e.preventDefault();
section.scrollIntoView({ behavior: 'smooth' });
});
.spacer {
height: 5000px;
background-color: pink;
}
<a id="link" href="#section">Go to section at the bottom</a>
<div class="spacer"></div>
<div id="section">This is a section at the bottom</div>
Codepen example.将输出 iFrame 打印为 PDF 以查看 PDF 中的链接。