首页 > 解决方案 > 重定向到某些 div 中的 url

问题描述

是否可以重定向到某些 div 中的 URL

喜欢

<div id="id45">
<! -- redirect to url if reached to this div content -->
</div>

标签: javascripthtml

解决方案


例如,您可以这样做:

function myFunction() {
  if (window.innerHeight + window.scrollY >= document.getElementById("id45").offsetTop) {
      window.open("https://www.example.com");
      window.removeEventListener("scroll", myFunction);
    }
}

window.addEventListener("scroll", myFunction);
<div style="width: 100%; height: 110vw; background-color: lightBlue;"></div>

<div id="id45" style="width: 100%; height: 100px; background-color: red;">
<! -- redirect to url if reached to this div content -->
</div>

对我来说,它有效,但不在这个 Stackoverflow 的片段中。它获得了完整浏览器窗口的高度,但是如果您将其复制到您的网站,我希望它会起作用。

注意:我的浏览器阻止了此窗口的打开,但这是正常的,如此处所述


推荐阅读