I'm trying to implement this background changer from removed after edits to my personal blog that only resides on my computer (not uploading to the internet), but I don't know what the js for it is? How would I go about adding it to my blog? I know there's the:
<body style="background-image : url();">
in the html file later followed by the:
<img src="" onmouseover="document.body.style.backgroundImage = 'url()';" width="20" height="20">
Is there anything else besides the js?
Edit: It seems this only works with 12x12 gifs? When I put my own images into the url places, the bg change won't work.
2nd Edit: I found the problem. I had my imgs not named properly.
Here is something that toggles between two images on the background of a div.
let images = ['https://www.gstatic.com/webp/gallery/3.jpg','https://www.gstatic.com/webp/gallery/1.jpg']; var currentImage = 1; let myDiv = document.getElementById("myBackground"); myDiv.addEventListener('mouseover', function(event) { currentImage = currentImage == 0 ? 1 : 0; event.target.style.backgroundImage = `url('${images[currentImage]}')`; });
#myBackground { background-image: url('https://www.gstatic.com/webp/gallery/1.jpg'); height: 300px; width: 300px; border: 2px; solid red; }
<div id="myBackground"></div>
Here is a version using just CSS, but limited to mouse over, resets when you leave the element.
#myBackground { background-image: url('https://www.gstatic.com/webp/gallery/1.jpg'); height: 300px; width: 300px; border: 2px; solid red; } #myBackground:hover { background-image: url('https://www.gstatic.com/webp/gallery/2.jpg'); }
<div id="myBackground"></div>
Here is a version the adds a class to the CSS on mouseover.
let myDiv = document.getElementById("myBackground"); myDiv.addEventListener('mouseover', function(event) { event.target.classList.add('myOverride'); });
#myBackground { background-image: url('https://www.gstatic.com/webp/gallery/1.jpg'); height: 300px; width: 300px; border: 2px; solid red; } #myBackground.myOverride { background-image: url('https://www.gstatic.com/webp/gallery/2.jpg'); }
<div id="myBackground"></div>
Your code will work just fine. No need of any other js code.
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.