javascript实现鼠标悬浮使图片居中页面显示
时间: 2023-11-29 07:04:03 浏览: 76
可以通过以下步骤实现:
1. 给图片设置一个固定宽度,以便于计算左右居中的位置。
2. 使用CSS将图片的位置设置为绝对定位,并将其左右居中。
```css
img {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
```
3. 监听图片的鼠标悬浮事件,当鼠标悬浮在图片上时,将其显示在页面中央。
```javascript
const img = document.querySelector("img");
img.addEventListener("mouseover", () => {
img.style.top = "50%";
img.style.left = "50%";
});
```
完整代码如下:
```html
<!DOCTYPE html>
<html>
<head>
<title>居中显示图片</title>
<style>
img {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 300px; /* 设置图片宽度 */
}
</style>
</head>
<body>
<img src="your-image-url.jpg" alt="your-image">
<script>
const img = document.querySelector("img");
img.addEventListener("mouseover", () => {
img.style.top = "50%";
img.style.left = "50%";
});
</script>
</body>
</html>
```
阅读全文
相关推荐















