滚动到名称为“foo"”的随机类
Scroll to random class with name "foo"
我已经这样做了div。我的标题是这样的
<div id="foo"></div>
<div id="foo2"></div>
<div id="foo3"></div>
<div id="foo4"></div>
<a class="bar">go to random div</a>
,然后使用jquery我去一个随机的div id。
$(document).ready(function() {
// Create an array of links
$("a.bar")
foo = new Array;
foo[0] = "#foo";
foo[1] = "#foo2";
foo[2] = "#foo3";
foo[3] = "#foo4";
$("a.bar").click(function() {
randomLink = Math.round(Math.random() * (foo.length - 1));
$("html, body").animate({
scrollTop: $(foo[randomLink]).offset().top + "px"
}, {
duration: 7000,
easing: "easeInOutExpo"
});
return false;
});
});
我现在想做相同的,但与一个类。一个HTML代码的例子是:
<div class="foo"></div>
<div class="foo"></div>
<div class="foo"></div>
<div class="foo"></div>
<a class="bar">go to random class</a>
考虑到<div class="foo"></div>
的数量不同,我该如何为这种情况做相应的jquery呢?
这个问题。
我不知道如何为每个类创建等效数组(而不是每个div)…因为它们是一样的……
任何想法?
您可以使用.eq()
函数,
var foo = $('.foo'); //Grab all the elements with the class foo
$("a.bar").click(function() {
randomLink = Math.round(Math.random() * (foo.length - 1));
$("html, body").animate({
scrollTop: foo.eq(randomLink).offset().top + "px"
//pass the random no to .eq() called over .foo collection
}, {
duration: 7000,
easing: "easeInOutExpo"
});
return false;
});
});
试试这个…
$("a.bar").click(function() {
randomLink = Math.round(Math.random() * (foo.length - 1));
$("html, body").animate({
scrollTop: $('.foo:eq('+ randomLink +')').offset().top + "px"
}, {
duration: 7000,
easing: "easeInOutExpo"
});
return false;
});
});
相关文章:
- 铬:“;未捕获的语法错误:意外的标记:"
- 可以设置“;文件名"发生错误时显示的内联脚本标记的
- JS表单提交"无法使用Chrome数据保护程序加载此页面.尝试重新加载页面.调试信息:POST CISmtuK
- 检测电话窃听,即:<a href="电话:xxx">在UIWebview上
- $(document).height()在刷新时随机化值(Safari 5.1.10)
- 使用“+="操作人员
- 使用当前日期生成随机id
- //而不是在src=“”上使用http://"属性
- "未捕获的语法错误:意外的标记}"
- 可以<脚本类型=“;text/javascript”>window.location=“/"</
- "实例范围”;TypeScript类的getter/setter
- Javascript复选框函数:;缺少:在属性id之后"
- "“;变量未引用正确的对象
- "日期“;AJAX请求返回的类型值未定义
- 得到"TypeError:无法读取属性'filename'未定义的“;调用“npm start
- Soundcloud api"未捕获的类型错误:无法读取属性'uri'“未定义”;
- "工具提示"jQuery插件坏了
- "锻造;React中的表达式
- 使用javascript"随机引用“;脚本,但跨越两个独立的元素
- "随机查找“;序列生成器