Genera una imagen de fondo aleatoria basada en un número aleatorio

Thought this would work but can't see where I'm going wrong. Just doesn't output the generated number and instead defaults to 0. The variable isn't updating.

Want to have a random image display as background, so I've created 5 images named bg-x.jpg.

Then generated a random number between 1 and 5 stored in var imgNumber

Entonces usa document.write to print out a style on the page with that imgNumber in place of the file URL.

<script type="text/javascript">
var imgNumber = 0;
function randomImage(imgNumber){
    var imgNumber = 1 + Math.floor(Math.random() * 5);
    console.log('Random number is ' + imgNumber);
}
window.onload = randomImage;
document.write('<style type="text/css"> body{background-image:url("images/bg/bg-' + imgNumber +'.jpg");}</style>');
</script>

Console works fine and shows a random number so I can only assume I've gone wrong here?

document.write('<style type="text/css"> body{background-image:url("images/bg/bg-' + imgNumber +'.jpg");}</style>');

preguntado el 28 de mayo de 14 a las 12:05

you have used local variable imgNumber in function so remove var of imgNumber inside function . This is problem of function scope. -

1 Respuestas

Creo que todo lo que necesitas hacer es reemplazar:

var imgNumber = 1 + Math.floor(Math.random() * 5);

¡Con

imgNumber = 1 + Math.floor(Math.random() * 5);

Inside your function, a new variable called imgNumber gets created and assigned, and the outer one isn't changed at all.

Edit: Try the following:

<script type="text/javascript">
function randomImage(){
    return 1 + Math.floor(Math.random() * 5);
}
document.write('<style type="text/css"> body{background-image:url("images/bg/bg-' + randomImage() + '.jpg");}</style>');
</script>

You don't even need a function, the following would work too:

<script type="text/javascript">
    document.write('<style type="text/css"> body{background-image:url("images/bg/bg-' + (1 + Math.floor(Math.random() * 5)) + '.jpg");}</style>');
</script>

contestado el 28 de mayo de 14 a las 12:05

Tried that but I think it must be an issue with global/local variables? The initialised variable is 0. I am only getting 0 so that var is not being updated. - Francesca

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.