jquery滚动到类名称 [英] jquery Scroll to class name

查看:296
本文介绍了jquery滚动到类名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下的Html代码,

 < div data-stored = storenowdata-save =saveclass =saveIcondata-unique =game>保存< / div> 

我写jquery滚动到下面的游戏No 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中找到解决方案。但是所有其他解决方案都与我的情况不同。

/ p>

  scrollTo = $(this).find('。saveIcon')。attr('data-unique',456); - >这是错误的

所以,当你试图定位一个元素时,你实际上是在设置'data - $'$
$ b

试试这个:

  scrollTo = $('。saveIcon'); 

工作代码:

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

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


I have the Html code like below,

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

And I write the jquery to scroll to the gameNo 456 like below.

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

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

I am using jQuery version 1.9. I am getting error in console:

Cannot read property 'top' of undefined

Is that not possible to scroll to class name instead of id?

But it is working fine in Firefox. But not in chrome or IE.

I try to find the solutions from stackoverflow. But all other solutions are different than my case.

解决方案

You are not targeting a DOM object, you are targeting a string.

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

So, while you are trying to target an element, you are actually setting the 'data-unique' to the '.saveIcon' element.

Try this:

scrollTo = $('.saveIcon');

Working code:

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

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

这篇关于jquery滚动到类名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆