简体   繁体   English

单击按钮后如何更改背景图像?

[英]How do I change background image upon button click?

Just want to click on button and have image that is on my desktop appear as background. 只是想单击按钮,让我桌面上的图像显示为背景。 I am using Tryit Editor v3.6 我正在使用Tryit Editor v3.6

I tried various file paths with more/fewer enclosing folders, tried messing with ",',/,\\ syntax...I just don't know enough 我尝试使用更多/更少的封闭文件夹尝试各种文件路径,尝试使用“,”,/,\\语法搞乱...我只是不够了解

<!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>

I also tried this: 我也试过这个:

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

I think you are using a TryIt Editor from w3schools. 我认为您正在使用w3schools的TryIt编辑器。

In that case, your file can't be accessed from your filesystem due to browser security policy which is an advanced topi. 在这种情况下,由于浏览器安全策略是高级topi,因此无法从文件系统访问您的文件。 You might have seen this kind of error in console while trying the above thing. 尝试上述操作时,您可能已经在控制台中看到这种错误。

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

I recommend to use image URLs which are available on google and not the images that are on your filesystem. 我建议使用Google上可用的图片URL,而不要使用文件系统上的图片。 Something like an eg. 像一个例子。 https://images.pexels.com/photos/414171/pexels-photo-414171.jpeg https://images.pexels.com/photos/414171/pexels-photo-414171.jpeg

If you use something like this it will work properly. 如果您使用这种方法,它将可以正常工作。

Try this, note that you cannot use a local image if you are working on an online editor 尝试此操作,请注意,如果您正在使用在线编辑器,则不能使用本地图像

<!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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM