我是一名 jQuery 新手,但已经非常接近实现我的结果了。基本上我想做的是以下过程:
从页面加载#anchor:
- 将散列转换为 ID 和类
- 垂直滚动到具有 anchor ID 的元素
- 水平滚动到具有类的不同元素
此外,同样的功能在页面上也有效。我正在尝试直接链接到 url.homl#hash,因此动画效果也适用于负载很重要。
我的例子在这里:http://willminnig.com/stacko/vertical-test-5.html#1908
到目前为止,我可以让它在页面加载时滚动到垂直 ID 而不是水平类,并且在页面完美加载后也是如此。它也会在页面完美加载后的第一次滚动到类,但在第一次之后是不稳定的行为。
这是我的(凌乱的)jQuery:
$(window).bind("load", function() {
var mainhash = window.location.href.split("#")[1];
$('html, body').animate({
scrollTop: $('#'+mainhash).offset().top
}, 900, 'swing');
$('a[href^="#"]').bind('click',function() {
var target = this.hash; //target is whole #hash
var whatever = '.pics .'+this.hash.split("#")[1];
$whatever = $(whatever);
$target = $(target); //$target is $(#hash)
$('.pics').animate({
scrollLeft: $whatever.offset().left
}, 900, 'swing');
$('html, body').stop().animate({
scrollTop: $target.offset().top
}, 900, 'swing');
window.location.hash = target; //target is whole #hash
});
});
任何解释我做错了什么的专业知识将不胜感激!此外,如果推荐,我可以更改滚动到元素的方式。 class/ID/hash 是我能想到的最好的。 非常感谢大家!
最佳答案
要在加载时触发水平滚动,您需要做的就是触发对 ID 等于“mainhash”的元素的点击。您可以通过在“加载”处理程序的末尾添加此行来实现此目的:
$('#'+mainhash).trigger('click');
至于不稳定的滚动,有点复杂。 $whatever 的 offset().left 是 $whatever 到窗口左侧的距离,不是它到 .pics 左侧的距离。当 .pics .scrollLeft() 为 0 时(即,当“1900”向左齐平时),您的动画将正常工作,否则不会。我认为解决方案是将 .pics .scrollLeft() 量添加到 $whatever 的 offset().left 中,这样你就可以得到 $whatever 从 .pics 左侧偏移的值:
scrollLeft: ($('.pics').scrollLeft() + $whatever.offset().left)
此外,我认为您在 #picswrap 和 .pics 上的 200% 宽度正在造成严重破坏,尽管我无法准确解释原因。我认为它们应该改为 100%。
关于javascript - jQuery 动画垂直滚动到一个元素和水平滚动到不同的元素同时从单个哈希标记/变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22517943/