首页 > 解决方案 > 如何在不单击href链接的情况下引用div id?

问题描述

我正在尝试在 python 中使用 streamlit 呈现网页,我想自动滚动到页面的特定部分。我不是 html 或 java 方面的专家,所以我很感激带有示例的解决方案。

所以我在页面底部有一个 div,例如,

st.markdown("<div id='linkto_bot'></div>", unsafe_allow_html=True)

我在顶部有这个 html 代码,

st.markdown("<a href='#linkto_bot'>Link to bottom</a>", unsafe_allow_html=True)

如图所示,它呈现一个链接,

在此处输入图像描述

单击链接后,我将滚动到div添加 is 的部分。

是否有可能被重定向到div而无需点击链接?

我尝试了以下但徒劳无功:

  1. st.markdown("a href='#linkto_bot', unsafe_allow_html=True) 在网上某处看到这个,但没有工作。
  2. 使用JavaScript,
html_string = '''
<script language="javascript">
    location.href = "#";
    location.href = "#linkto_bot";
</script>
'''
components.html(html_string)

这也不起作用。

标签: javapythonhtml

解决方案


你可以使用javascript函数scrollIntoView()

document.getElementById('linkto_bot').scrollIntoView();

推荐阅读