简体   繁体   中英

How do I click an image to make it my page background?

So, in short, I am a bit new to most of this. What I need to do is make a panel of four different images. I have already done that, and now I need to make it so whatever image I click on will become the background of the page. I'm sorry if I have explained this poorly, but does anybody know how I would code this in javascript? If you could help me, I would greatly appreciate it.

Assign the source of the image to the background-image property of the document body.

 // Attach an event listener to the container, and // add a listener to it that calls the `handleClick` function. const images = document.querySelector('.images'); images.addEventListener('click', handleClick, false); // Check to see if the element ciicked on is an // image, and then assign the image src to the // background-image property of the document body function handleClick(e) { if (e.target.matches('img')) { const { src } = e.target; document.body.style.backgroundImage = `url(${src})`; } }
 body { background-size: cover; background-repeat: no-repeat; } img:hover { cursor: pointer; }
 <div class="images"> <img src="https://dummyimage.com/75x75/000/fff&text=1" /> <img src="https://dummyimage.com/75x75/575/fff&text=2" /> <img src="https://dummyimage.com/75x75/a8d/fff&text=3" /> <img src="https://dummyimage.com/75x75/bbc/fff&text=4" /> </div>

Additional documentation

This not the best solution but i think it can help you

    <html>
    <body>
    /*You can make img click able and onclick like button*/
    <img src="this is picture path" onclick="function">
    <script>
    /* Function change background*/
    function function() {
    /* Command js and picture path inside 'this' and url with css command inside "this" actually just copy the code, no-repeat right top just a some css setting */
      document.body.style.background = "url('img_tree.png') no-repeat right top";
/* You see "body" tag right? It change body background*/
    }
    </script>
    
    </body>
    </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