停止图像显示在用户输入Javascript

Cease Image Display on User Input Javascript

本文关键字:用户 输入 Javascript 显示 图像      更新时间:2023-09-26

我正在尝试与qualtrics.com JS API接口,并遇到麻烦,因为下面的代码不会停止在其动画循环结束时显示图像。Qualtrics是一个调查托管网站,我基本上需要所有的图像显示在动画循环编码下面消失一旦调查受访者点击下一个按钮。addOnLoad()函数是质量API的一部分,它正在工作(作为函数的警报部分),但我认为删除(imageLinks[I])有问题;选项,因为图像一直在显示。有什么建议吗?

var imageLinks = ["http://i.imgur.com/iUjHm4e.jpg",
    "http://i.imgur.com/89Bh81C.jpg",
    "http://i.imgur.com/qKecE0F.jpg",
    "http://i.imgur.com/s5LzrE1.jpg",
    "http://i.imgur.com/thRmkE8.jpg",
    "http://i.imgur.com/mjfqeKv.jpg",
    "http://i.imgur.com/w9EpXNq.jpg",
    "http://i.imgur.com/b2rP5RQ.jpg",
    "http://i.imgur.com/NDLm5QQ.jpg",
    "http://i.imgur.com/7nohNKf.jpg",
    "http://i.imgur.com/4Qtz8KB.jpg",
    "http://i.imgur.com/xTwSsBe.jpg",
    "http://i.imgur.com/KwXNQjR.jpg",
    "http://i.imgur.com/5BVvvci.jpg",
    "http://i.imgur.com/bU0jnnD.jpg",
    "http://i.imgur.com/YKy6K6u.jpg",
];
function display(src) {
    var img = document.createElement("img");
    img.src = src;
    //img.style.position = "absolute";
    //img.style.left = "270px";
    //img.style.top = "300px";
    document.body.appendChild(img);
    return img;
}

function remove(img) {
    document.body.removeChild(img);
}

i = 0;
function animation_loop() {
    var im = display(imageLinks[i]);
    setTimeout(function () {
        i++;
        if (i < imageLinks.length) {
            animation_loop();
        remove(im);}
    }, 150);
};
animation_loop();
Qualtrics.SurveyEngine.addOnload(function ()
{
    this.questionclick = function(event,element){
        if(element.type == "radio") {
            alert("Good job choosing an answer!");
            remove(imageLinks[i]);
        }
    }
});

JSFiddle: https://jsfiddle.net/cbjrobertson/o0onrxa1/

你需要清除click事件的超时时间;这将防止内部函数再次触发,从而打破循环。

对于删除函数,需要再次传入DOM元素,就像处理循环一样。像这样:

var loopTimeout;
var im;
function animation_loop() {
    im = display(imageLinks[i]);
    loopTimeout = setTimeout(function () {
        i++;
        if (i < imageLinks.length) {
            remove(im);
            animation_loop();
        }
    }, 150);
};
Qualtrics.SurveyEngine.addOnload(function ()
{
    this.questionclick = function(event,element){
        if(element.type == "radio") {
            clearTimeout(loopTimeout);
            alert("Good job choosing an answer!");
            remove(im);
        }
    }
});