如何在文档加载时自动启动图像滑块?

时间:2013-09-16 16:00:13

标签: javascript jquery

我对JavaScript& jQuery的。我正在尝试一些图像滑块的代码,它可以在图像点击事件中正常工作。但是,我希望它在文档加载后自行运行。我怎样才能做到这一点?我试图将代码放在$(document).ready()中,但它不会那样工作。这是我的代码:

<script>
var total = 4;
var present = 1;
var next = 2;
$(document).ready(function () {
    $("#right").click(function () {
        present_slide = "#slide" + present;
        next_slide = "#slide" + next;
        $(present_slide).css("top", "200px");
        $(next_slide).css("top", "0px");
        present++;
        next++;
        if (present == (total + 1)) {
            present = 1;
            next = 2;
            for (i = 1; i <= 4; i++) {
                $("#slide" + i).css("top", "200px");
            }
            $("#slide1").css("top", "0px");
        }
    });
});
</script>

此处 - #right是与img元素关联的ID。 #slide1#slide2等是与包含多个图片的div关联的ID。

5 个答案:

答案 0 :(得分:1)

$(document).ready(function (){

$( "#right" ).trigger( "click" );

});

答案 1 :(得分:0)

尝试将$(document).ready()替换为$(window).onload = function(){ ... }

答案 2 :(得分:0)

删除$("#right").click(function () {或添加$('#right').trigger('click')

var total = 4;
var present = 1;
var next = 2;
$(document).ready(function () {
    present_slide = "#slide" + present;
    next_slide = "#slide" + next;
    $(present_slide).css("top", "200px");
    $(next_slide).css("top", "0px");
    present++;
    next++;
    if (present == (total + 1)) {
        present = 1;
        next = 2;
        for (i = 1; i <= 4; i++) {
            $("#slide" + i).css("top", "200px");
        }
        $("#slide1").css("top", "0px");
    }
});

或者

var total = 4;
var present = 1;
var next = 2;
$(document).ready(function () {
    $("#right").click(function () {
        present_slide = "#slide" + present;
        next_slide = "#slide" + next;
        $(present_slide).css("top", "200px");
        $(next_slide).css("top", "0px");
        present++;
        next++;
        if (present == (total + 1)) {
            present = 1;
            next = 2;
            for (i = 1; i <= 4; i++) {
                $("#slide" + i).css("top", "200px");
            }
            $("#slide1").css("top", "0px");
        }
    }).trigger('click');
});

答案 3 :(得分:0)

当窗口加载

时,您可以手动触发图像的“单击”事件
$(window).load(function() {
  $("#right").trigger('click');
}

一旦加载了所有资源,这将触发点击。

答案 4 :(得分:-1)

在脚本块的底部,放置以下行:

$("#right").trigger('click');