GIFs changing randomly

2019-07-23 22:00发布

问题:

I got a problem with GIFs and Javascript. I got different GIF-animations which are all the same format and I want them to change randomly after they are played one time.

I tried to solve this with Javascript but I only could make it work with an exact time to make the change and not when each GIF-animation is finished (they are all finishing at different times).

<html>
<head>
<script type="text/javascript">
<!--
var ima = [];

ima[0] = 'bilder/bild1.gif';
ima[1] = 'bilder/bild2.gif';
ima[2] = 'bilder/bild3.gif';
ima[3] = 'bilder/bild4.gif';

function BildWechsel()
{
    var num = Math.random();
    var ran = Math.floor((ima.length - 1) * num);

    document.images['wechsel'].src = ima[ran];
}

onload = function ()
{
    window.setInterval(function () { BildWechsel(); }, 10000);
}
//-->
</script>

</head>
<body>

<img id="wechsel" src="bilder/bild1.gif" border="0" alt="">

</body>
</html>

Is there any possibility to make this work? And if not in a browser, how else can you maybe make it work?

回答1:

I would rewrite the Javascript like this:

window.onload = function () {

    var images = [
            {src:'bilder/bild1.gif',delay:3000},
            {src:'bilder/bild2.gif',delay:2000},
            {src:'bilder/bild3.gif',delay:1500},
            {src:'bilder/bild4.gif',delay:4000}
        ],
        element = document.images['wechsel'],
        change_image = function () {
            var image = images[ Math.floor( Math.random() * images.length ) ];
            // (Math.random()*images.length)>>0 would be a lot faster

            element.src = image.src;

            setTimeout(change_image, image.delay);
        };

    setTimeout(change_image, 10000);

};

The delay would change based on the image you currently have.

This has a few speed improvements and the code is as simple as it can get.

This was untested!

Here is a (slightly) changed version to change the text color:

window.onload = function () {

	var colors = [
			{name:'red',delay:3000},
			{name:'yellow',delay:1000},
			{name:'green',delay:2300},
			{name:'blue',delay:2600},
			{name:'pink',delay:1300},
			{name:'purple',delay:500},
		],
		element = document.getElementById('span'),
		change_color = function () {
			var color = colors[ ( Math.random() * colors.length )>>0 ];

			element.style.color = color.name;
			
			setTimeout(change_color, color.delay);
		};
		
	setTimeout(change_color, 2000);
	
};
<span id="span" style="background:black;font-family:sans-serif;font-size:20px;font-weight:bold;padding:10px;">I change color!</span>



回答2:

Well, first off, there are many considerations here.

You first need to understand that you can have a multi-dimensional array consisting of a series of objects, instead of plain strings (which is what you have now). I suggest you do some reading on this here: (take a look at Mozilla's Developer Network, or google for it).

Now, you cannot do that with an interval, because intervals happen at a preset, well, interval. You need a timeout - but timeouts happen only once.

You can see where this is going, right? So you need to call the timeout again once the previous timeout has finished - that goes to a concept of "callback" (google "javascript callbacks").

In any case, I've put up a very simple example for you in JSFiddle - it doesn't solve your problem 100%, because I think it would be cool if you'd put some thinking into how this all works, but this should get you at least something to work with (also on JSFiddle - http://jsfiddle.net/Nitrium/kyvbnxfv/)

imab = []; 

imab[0] = {
    image: 'bilder/bild1.gif', 
    time: 1000
}

imab[1] = {
    image: 'bilder/bild2.gif', 
    time: 500
}

imab[2] = {
    image: 'bilder/bild3.gif', 
    time: 2500
}

imab[3] = {
    image: 'bilder/bild4.gif', 
    time: 100
}

function BildWechselB() {
    var num = Math.random();
    var ran = Math.floor((imab.length - 1) * num);

    return imab[ran];
}

var interval;

function callBack (imageSrc) {

    printImage(imageSrc);

    clearInterval(interval);

    var newRandomImage = BildWechselB();
    interval = window.setTimeout(callBack, newRandomImage.time, newRandomImage.image)
}

function printImage (src) {
    var imageSrc = document.createTextNode(src);
    var bodyTag = document.getElementsByTagName('body');
    bodyTag[0].appendChild(imageSrc);
}

var firstRandomImage = BildWechselB();

interval = window.setTimeout(callBack, firstRandomImage.time, firstRandomImage.image);

Hope it helps!