Javascript jQuery动画从单个哈希标记/变量垂直滚动到一个元素,同时水平滚动到不同的元素
我是一个jQuery新手,但已经非常接近实现我的结果。基本上,我试图做的是以下过程: 从页面加载#锚定:Javascript jQuery动画从单个哈希标记/变量垂直滚动到一个元素,同时水平滚动到不同的元素,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我是一个jQuery新手,但已经非常接近实现我的结果。基本上,我试图做的是以下过程: 从页面加载#锚定: $(window).bind("load", function() { var mainhash = window.location.href.split("#")[1]; $('html, body').animate({ scrollTop: $('#'+mainhash).offset().top }, 900, 'swing');
$(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
});
- 将哈希转换为ID和类
- 垂直滚动到具有锚ID的元素
- 水平滚动到具有类的其他元素
$(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”的元素即可。您可以通过在“load”处理程序的末尾添加此行来实现这一点:
$('#'+mainhash).trigger('click');
至于不稳定的滚动,嗯,有点复杂$whatever's offset().left是$whater与窗口左侧的距离,而不是它与.pics左侧的距离。当.pics.scrollLeft()为0时(即当“1900”向左齐平时),动画将正常工作,否则将无法正常工作。我认为解决方案是将.pics.scrollLeft()金额添加到$whater's offset().left,这样您就可以从.pics的左侧获得$whater's offset的值:
scrollLeft: ($('.pics').scrollLeft() + $whatever.offset().left)
此外,我认为你在#picswrap和.pics上的200%宽度造成了巨大的破坏,尽管我无法确切解释原因。我认为应该将其更改为100%。感谢您的帮助-现在它工作得非常好!这让我发疯,你不知道我有多感激你的洞察力!