我用 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;
});
});
我现在想做同样的事情,但要用一个类(class)。因此,示例 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>
我将如何为这种情况做等价的 jquery,请记住有不同数量的 <div class="foo"></div>
。 ?
问题。
我不知道如何为每个类(而不是每个 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;
});
});
关于javascript - 滚动到名称为 "foo"的随机类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24219832/