简体   繁体   中英

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

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.

In that case, your file can't be accessed from your filesystem due to browser security policy which is an advanced 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. Something like an eg. 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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