Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

275
Visualizações
Random Background Images

I wanted to have a random background image each time a page loads, from a list of 5 images.

I was trying to follow this questions,

Random background images CSS3

but it never gets officially answered, and I can't quite make it work. It feels like it should work though, and I might be missing something simple.

I want to put this in the _Layout page, so it applies to each page. It's kind of TMI, but I'm in VS2019, asp core mvc in c#.

This is what I got:

<head>
<style>...</style>
<script type="text/javascript">
        var totalCount = 8;
        function ChangeIt() {
            var num = Math.ceil(Math.random() * totalCount);
            document.body.background = 'assets/bgImages/' + num + '.jpg';
            document.body.style.backgroundRepeat = "repeat";    // Background repeat
        }
    </script>
</head>
<body>...</body>

</html>
<script type="text/javascript">
    ChangeIt();
</script>
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

When you access the background property on the body, you're missing the ".style" part and you need to use "url('...')" to set images as background. You can even set image and repeat at the same time.

Here's an example: https://jsfiddle.net/pg1u0rn6/

const randomId = 10836835;
const pexelId = '60597/dahlia-red-blossom-bloom-60597';

document.body.style.background = "url('https://wallpaper.dog/large/" + randomId + ".jpg') repeat";
document.querySelector('.inner').style.background = "url('https://images.pexels.com/photos/" + pexelId + ".jpeg')";
body {
  background: red;
  height: 100vh;
  margin: 0;
  padding: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

.inner {
  width: 300px;
  height: 300px;
  background-size: cover !important;
}
<div class="inner"></div>

In you case:

document.body.style.background = "url('assets/bgImages/" + num + ".jpg') repeat";
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda