<a class="scrollbutton" data-scroll="#somethingonpage"
onchange="scrollto(this);">something on page</a>
<div id="somethingonpage">scrolls to here when you click on the link above</a>
<script type="text/javascript">
function scrollto(element) {
// get the element on the page related to the button
var scrollToId = element.getAttribute("data-scroll");
var scrollToElement = document.getElementById(scrollToId);
// make the page scroll down to where you want
// ...
}
</script>
使用jQuery:
<a class="scrollbutton" data-scroll="#somethingonpage">something on page</a>
<div id="somethingonpage">scrolls to here when you click on the link above</a>
<script type="text/javascript">
$(".scrollbutton").click(function () {
// get the element on the page related to the button
var scrollToId = $(this).data("scroll");
var scrollToElement = document.getElementById(scrollToId);
// make the page scroll down to where you want
// ...
});
</script>
注意:如果你真的想要一个“按钮”而不是“链接”,你可以真正使用任何元素并使其可点击,例如:
<button class="scrollbutton" data-scroll="#somethingonpage">something on page</button>
5 回答
通过为其指定ID,将项目标记在您要重定向到的同一页面上 . 假设id = "itemId",然后使用
<a class="btn btn-large btn-primary" href="#itemId">Democracy</a>
. 单击该按钮时,您将被重定向到包含该项目的页面部分 .这假设您不是在谈论向下滚动到常规锚点,而是想要滚动到页面上的实际HTML元素 .
我不确定jQuery是否适合你,但如果你使用Bootstrap,我想它确实如此 . 如果是这样,你可以绑定到你的按钮的“点击”事件,并在那里放一些JavaScript代码来处理滚动 . 通常,您可以使用“data”属性(例如data-scroll =“my-element-id”)将链接/按钮与要滚动到的元素相关联 .
如果没有jQuery,你必须创建一个包含所描述代码的函数,并放入一个引用你的函数的onclick属性,并将“this”作为参数传递给你的函数,这样你就可以获得对该链接的引用/ button元素调用它 .
有关用于实际滚动到相应元素的代码,请查看以下文章:
How to go to a specific element on page?
没有jQuery的快速示例:
使用jQuery:
注意:如果你真的想要一个“按钮”而不是“链接”,你可以真正使用任何元素并使其可点击,例如:
尝试:
嘿试试这个: -
然后你想去你的网站: -
u may just place the line below wherever you want,
希望这对你有用
This is the easy way to do it