<div id="background"></div>
<script>
  var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
  var counter = 0;

  function changeBackground() {
    counter++;
    if (counter >= images.length) {
      counter = 0;
    }
    var url = "url('"+ images[counter] + "')";
    document.getElementById("background").style.backgroundImage = url;
  }

  setInterval(changeBackground, 5000); // 每5秒钟切换一次图片
</script>
<h2>网页背景图片自动切换</h2>
<p>网页背景图片自动切换可以通过 JavaScript 代码实现。以下是一个简单的实现方式:</p>
<ol>
<li>在 HTML 中添加一个具有固定高度和宽度的 div 元素,作为背景容器:</li>
</ol>
<pre><code class="language-html">&lt;div id=&quot;background&quot;&gt;&lt;/div&gt;
</code></pre>
<ol start="2">
<li>在 JavaScript 中定义一个数组,包含需要轮换的图片 URL:</li>
</ol>
<pre><code class="language-javascript">var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
</code></pre>
<ol start="3">
<li>创建一个计数器变量,用于跟踪当前显示的图片:</li>
</ol>
<pre><code class="language-javascript">var counter = 0;
</code></pre>
<ol start="4">
<li>定义一个函数,用于在背景容器中显示下一张图片:</li>
</ol>
<pre><code class="language-javascript">function changeBackground() {
  counter++;
  if (counter &gt;= images.length) {
    counter = 0;
  }
  var url = &quot;url('&quot;+ images[counter] + &quot;')&quot;;
  document.getElementById(&quot;background&quot;).style.backgroundImage = url;
}
</code></pre>
<ol start="5">
<li>使用定时器,每隔一段时间调用 changeBackground 函数,以实现自动切换背景图片的效果:</li>
</ol>
<pre><code class="language-javascript">setInterval(changeBackground, 5000); // 每5秒钟切换一次图片
</code></pre>
<p>完整的代码如下:</p>
<pre><code class="language-html">&lt;div id=&quot;background&quot;&gt;&lt;/div&gt;

&lt;script&gt;
  var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
  var counter = 0;

  function changeBackground() {
    counter++;
    if (counter &gt;= images.length) {
      counter = 0;
    }
    var url = &quot;url('&quot;+ images[counter] + &quot;')&quot;;
    document.getElementById(&quot;background&quot;).style.backgroundImage = url;
  }

  setInterval(changeBackground, 5000);
&lt;/script&gt;
</code></pre>
网页背景图片自动切换 JavaScript 实现

原文地址: https://www.cveoy.top/t/topic/mM57 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录