gpt4 book ai didi

jquery - 根据事件链接水平居中滚动

转载 作者:行者123 更新时间:2023-11-28 09:07:55 24 4
gpt4 key购买 nike

如何使用 jQuery 根据事件链接水平居中滚动?

我正在使用 overflow-x: scroll; 来启用水平滚动,但我希望滚动根据事件链接居中。

这就是我要实现的目标:

enter image description here

Example

$(document).ready(function () {
$('a[href^="#"]').on('click', function (e) {
e.preventDefault();
$(document).off("scroll");

$('a').each(function () {
$(this).removeClass('active');
})
$(this).addClass('active');
});
});

function onScroll(event){
$('#menu-center a').each(function () {
var currLink = $(this);
var refElement = $(currLink.attr("href"));
currLink.removeClass("active");
});
}

最佳答案

据我所知,当您登陆页面时,您需要使用 JavaScript 自动滚动。你可以做一些像...

$(document).ready(function () {
$('a[href^="#"]').on('click', function (e) {
e.preventDefault();
$(document).off("scroll");

$('a').each(function () {
$(this).removeClass('active');
})
$(this).addClass('active');
var myScrollPos = $('a.active').offset().left + $('a.active').outerWidth(true)/2 + $('.menu').scrollLeft() - $('.menu').width()/2;
$('.menu').scrollLeft(myScrollPos);
});
});

您可以调整 myScrollPos 使其停止在您想要的位置,这应该使它滚动到事件按钮的左侧。分解如下!

$('a.active').offset().left + $('a.active').outerWidth(true)/2

这让我们得到了按钮与它所包含的元素的可见边缘的距离,在本例中是菜单,然后减去按钮宽度的一半以获得返回值作为按钮的中心而不是边缘。它不包括在父级上完成的任何滚动,因此我们从这里添加

+ $('.menu').scrollLeft()

通过这种方式,我们可以得到菜单项距左侧的距离,加上当前的滚动位置。两者的结合让我们在每个按钮之间获得一致的滚动坐标。然后,把它包起来,

- $('.menu').width()/2

将滚动偏移菜单宽度的负 1/2,有效地将按钮居中!

*更新了最终解决方案!

关于jquery - 根据事件链接水平居中滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38206868/

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