2

只想单击按钮并将我桌面上的图像显示为背景。我正在使用 Tryit Editor v3.6

我尝试了具有更多/更少封闭文件夹的各种文件路径,尝试弄乱“,”,/,\语法......我只是不太了解

<!DOCTYPE html>
<html>
  <body>
    <button onclick="myFunction()">change background</button>

    <script>
      function myFunction() {
        document.body.style.backgroundImage ="/Users/mcgeheer/Desktop/testpic.png"
      }
    </script>
  </body>
</html>

我也试过这个:

document.body.style.backgroundImage ="url( '/Users/mcgeheer/Desktop/testpic.png')";
4

2 回答 2

0

我认为您使用的是 w3schools 的 TryIt 编辑器。

在这种情况下,由于浏览器安全策略是高级主题,因此无法从文件系统访问您的文件。在尝试上述操作时,您可能已经在控制台中看到了这种错误。

Not allowed to load local resource: file:////Users/mcgeheer/Desktop/testpic.png

我建议使用 google 上提供的图像 URL,而不是文件系统上的图像。诸如此类的东西。https://images.pexels.com/photos/414171/pexels-photo-414171.jpeg

如果您使用类似的东西,它将正常工作。

于 2019-07-17T20:39:57.040 回答
0

试试这个,请注意,如果您正在使用在线编辑器,则不能使用本地图像

<!DOCTYPE html>
<html>
<style>
  .background {
    background: black;
    height: 100px;
    width: 100px;
    color: white;
  }
</style>
<body>

<div id="background" class="background">Background</div>

<button onclick="myFunction()">change background</button>
</body>
<script>
    function myFunction() {
      document.getElementById('background').style.cssText = "background-image: url('http://images5.fanpop.com/image/photos/29800000/Blue-Rose-roses-29859433-449-300.jpg');"
    }
</script>
</html> 
于 2019-07-18T10:40:59.450 回答