ZhihanXing 发表于 2023-5-28 00:49:32

js中不能用一个元素的backgroudImage去替换另一个元素的backgroudImage吗?

要求:当用户点击相应的按钮后,将网页body的backgroudImage清除并替换成所点击按钮的backgroudImage
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>案例-百度换肤</title>
    <style>
      *{
            margin: 0;
            padding: 0;
      }
      body{
            background-image: url(image/pic1.png);
            background-size: cover;
      }
      button{
            width: 90px;
            height: 40px;
      }
      .b1{
            background-image: url('image/pic1.png');
      }
      .b2{
            background-image: url('image/pic2.png');
      }
      .b3{
            background-image: url('image/pic3.png');
      }
      .b4{
            background-image: url('image/pic4.png');
      }
      .b5{
            background-image: url('image/pic5.png');
      }
    </style>
</head>
<body>
    <button class="b1"></button>
    <button class="b2"></button>
    <button class="b3"></button>
    <button class="b4"></button>
    <button class="b5"></button>
    <script>
      //获取所有元素
      const buttons = document.querySelectorAll('button')
      const body = document.body
      //使用排他算法替换背景
      for(let i=0;i<buttons.length;i++){
            buttons.onclick = function(){
                //清楚当前背景
                body.style.backgroundImage = 'none'
                //根据当前按钮更换背景
                body.style.backgroundImage = "url("+this.style.backgroudImage+")"
            }
      }
    </script>
</body>
</html>

isdkz 发表于 2023-5-28 01:09:39

你的代码逻辑是对的,但是在获取元素的backgroundImage时,拼写错误了。应该是"backgroundImage"而不是"backgroudImage"。

修改后的JavaScript代码如下:

<script>
    //获取所有元素
    const buttons = document.querySelectorAll('button')
    const body = document.body
    //使用排他算法替换背景
    for(let i=0;i<buttons.length;i++){
      buttons.onclick = function(){
            //清除当前背景
            body.style.backgroundImage = 'none'
            //根据当前按钮更换背景
            body.style.backgroundImage = "url("+this.style.backgroundImage+")"
      }
    }
</script>


这样,点击按钮后就能把body的背景图片更换为按钮的背景图片了。

请注意,由于路径问题,可能还需要在"backgroundImage"属性前加上"window.getComputedStyle(this)"来获取计算后的样式属性。

<script>
    //获取所有元素
    const buttons = document.querySelectorAll('button')
    const body = document.body
    //使用排他算法替换背景
    for(let i=0;i<buttons.length;i++){
      buttons.onclick = function(){
            //清除当前背景
            body.style.backgroundImage = 'none'
            //根据当前按钮更换背景
            body.style.backgroundImage = window.getComputedStyle(this).backgroundImage
      }
    }
</script>


这样可以更好地获取元素实际渲染的背景图片。
页: [1]
查看完整版本: js中不能用一个元素的backgroudImage去替换另一个元素的backgroudImage吗?