简体   繁体   English

Javascript onmouseover背景图片更改

[英]Javascript onmouseover background image change

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: 在html文件中,后面跟着:

<img src="" onmouseover="document.body.style.backgroundImage = 'url()';" width="20" height="20"> 

Is there anything else besides the js? 除了js还有其他东西吗?

Edit: It seems this only works with 12x12 gifs? 编辑:看来这仅适用于12x12 gif? When I put my own images into the url places, the bg change won't work. 当我将自己的图片放入url位置时,bg更改将不起作用。

2nd Edit: I found the problem. 2nd编辑:我发现了问题。 I had my imgs not named properly. 我的img命名不正确。

Here is something that toggles between two images on the background of a div. 这是在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. 这是一个仅使用CSS的版本,但仅限于将鼠标悬停在离开元素时重置。

  #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. 这是一个在鼠标悬停时向CSS添加类的版本。

 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. 无需任何其他js代码。

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

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