gpt4 book ai didi

javascript - 滚动到页面上值 = 'x' 的位置

转载 作者:行者123 更新时间:2023-11-28 19:40:22 24 4
gpt4 key购买 nike

我想在我的页面顶部有一个链接,例如:-

<a href="#" id="example">Scroll to</a>

基本上我想做以下事情:-

当点击 #example 时,我希望它滚动到页面上 h1 value = 'test' 的位置:-

$('#example').bind('click',function() {

// GO TO LOCATION ON PAGE WHERE h1 value ='test' ( <h1> = 'test' </h1> )

});

这可以做到吗?

我知道我可以为此使用 anchor ,但我使用的菜单插件没有添加这个,所以我需要根据值是什么,因为这是不同部分之间唯一唯一的东西。

最佳答案

使用 .filter() 查找目标元素方法,然后使用其 .offset() (查找其在文档中的位置)和 .animate()页面的 scrollTop 属性

$('#example').bind('click',function(e) {
e.preventDefault();

var target = $('h1').filter(function(){ return $(this).text() == 'test' ;});

$('html,body').animate( {
scrollTop: target.offset().top
});

});

演示地址:http://jsfiddle.net/Lc8gg7pm/1/

关于javascript - 滚动到页面上值 = 'x' 的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25203049/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com