html js 鼠标移动到图片上时,修改背景为该图片
时间: 2024-05-04 12:18:33 浏览: 41
可以通过JavaScript来实现这个效果。
首先,需要获取到图片元素和目标元素。可以使用getElementById()方法获取元素。
```html
<img id="image" src="image.jpg">
<div id="target"></div>
```
```javascript
const image = document.getElementById("image");
const target = document.getElementById("target");
```
接下来,需要监听鼠标移动事件,可以使用addEventListener()方法。
```javascript
image.addEventListener("mousemove", function(event) {
// 鼠标移动时的操作
});
```
在鼠标移动时,需要获取鼠标的位置,以及图片的位置和大小。可以使用event对象的pageX和pageY属性来获取鼠标位置,以及getBoundingClientRect()方法来获取图片的位置和大小。
```javascript
const mouseX = event.pageX;
const mouseY = event.pageY;
const rect = image.getBoundingClientRect();
const imgX = rect.left;
const imgY = rect.top;
const imgWidth = rect.width;
const imgHeight = rect.height;
```
然后,需要判断鼠标是否在图片内部。如果在图片内部,就将目标元素的背景设置为当前图片。
```javascript
if (mouseX > imgX && mouseX < imgX + imgWidth &&
mouseY > imgY && mouseY < imgY + imgHeight) {
target.style.backgroundImage = "url(" + image.src + ")";
} else {
target.style.backgroundImage = "";
}
```
完整代码如下:
```html
<img id="image" src="image.jpg">
<div id="target"></div>
<script>
const image = document.getElementById("image");
const target = document.getElementById("target");
image.addEventListener("mousemove", function(event) {
const mouseX = event.pageX;
const mouseY = event.pageY;
const rect = image.getBoundingClientRect();
const imgX = rect.left;
const imgY = rect.top;
const imgWidth = rect.width;
const imgHeight = rect.height;
if (mouseX > imgX && mouseX < imgX + imgWidth &&
mouseY > imgY && mouseY < imgY + imgHeight) {
target.style.backgroundImage = "url(" + image.src + ")";
} else {
target.style.backgroundImage = "";
}
});
</script>
```
阅读全文