jQuery滚动到类名

20

我有以下的 Html 代码:

<div data-stored="storenow" data-save="save" class="saveIcon" data-unique="game">Save</div>

我编写了以下 jQuery 代码,用于滚动到游戏编号为 456 的位置。

var container = $("html,body");
var scrollTo = $(this).find('.saveIcon').attr('data-unique', 456);

 container.animate({
    scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop()
});

我正在使用jQuery版本1.9。控制台显示错误:

无法读取未定义的属性“top”

是否无法滚动到类名而不是id?

但它在Firefox中正常工作。但在Chrome或IE中无法正常工作。

我尝试从stackoverflow上寻找解决方案。但所有其他解决方案与我的情况不同。


5
jQuery 9??? John Resig会震惊 ;) (注:原文中的“9”可能是笔误或打错,因为jQuery版本号最高仅到3.x.x) - Amit Joki
4个回答

40

你的目标不是一个 DOM 对象,而是一个字符串。

scrollTo = $(this).find('.saveIcon').attr('data-unique', 456); -> this is wrong

所以,在您尝试定位一个元素时,实际上是将 'data-unique' 设置为 '.saveIcon' 元素。

请尝试这样做:

scrollTo = $('.saveIcon');

可运行的代码:

var $container = $("html,body");
var $scrollTo = $('.saveIcon');

$container.animate({scrollTop: $scrollTo.offset().top - $container.offset().top + $container.scrollTop(), scrollLeft: 0},300); 

我有很多数据唯一值,例如456、567、789等等,需要滚动到特定的数据唯一值。比如说,这里是456。请告诉我,如果我错了的话。 - alagu
你可以尝试使用这种选择器:var $scrollTo = $('.saveIcon[data-unique="456"]'); - RazvanDH
2
只是想说谢谢你发布这个答案!它帮助我修复了我正在开发的游戏中的菜单系统,使滚动到元素的对齐完美无缺。 - Dexx

3

1
这个只被火狐浏览器支持,所以不是一个很好的解决方案,这很遗憾,因为它在火狐浏览器上简单易用且效果良好。 - alsobubbly
@alsobubbly 浏览器兼容性可以追溯到 IE8,我很确定它能够工作,只是不提供其他选项。 - vico
根据您提供的链接(https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView),大多数浏览器仅具有基本支持,只有FireFox支持scrollIntoViewOptions。因此,是的,它可以工作,但它是实验性技术,因此随着规范的变化,行为可能会在将来的浏览器版本中发生变化。不过,如果能广泛支持这一功能将是非常好的。 - alsobubbly

3

这两个代码对我非常有效,第一个将带您滚动到页面顶部,但如果您想滚动到某个特定的div,请使用第二个代码并添加您的div id。

$('body, html, #containerDiv').scrollTop(0);
document.getElementById('yourDivID').scrollIntoView();

如果您想通过类名滚动,请使用以下代码。
var $container = $("html,body");
var $scrollTo = $('.main-content');

$container.animate({scrollTop: $scrollTo.offset().top - $container.offset().top + 
$container.scrollTop(), scrollLeft: 0},300);

1

我正在使用以下纯JavaScript代码,请尝试在你的代码中使用:

$('a.smooth-scroll[href*=#]:not([href=#])').click(function () {
    if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
        if (target.length) {
            $('html,body').animate({
                scrollTop: target.offset().top
            }, 1000);
            return false;
        }
    }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接