滚动到名称为“foo"”的随机类

Scroll to random class with name "foo"

本文关键字:quot 随机 foo 滚动      更新时间:2023-09-26

我已经这样做了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;
    });
});