JS实现鼠标移动到缩略图显示大图的图片放大效果


要实现鼠标移动到缩略图上显示大图的图片放大效果,你可以使用HTML和JavaScript结合CSS来完成。这里提供一个基本的实现方式:

### HTML


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Zoom on Hover</title>
<link rel="stylesheet" href="style.css">
</head>
<body>

<div class="image-container">
    <img src="small-image.jpg" alt="Thumbnail" class="thumbnail" onmouseover="showLargeImage(event)" onmouseout="hideLargeImage()">
    <div class="large-image-container" id="largeImageContainer" style="display:none;">
        <img src="large-image.jpg" alt="Large Image" class="large-image">
    </div>
</div>

<script src="script.js"></script>
</body>
</html>

### CSS (style.css)


.image-container {
    position: relative;
    display: inline-block;
}

.thumbnail {
    width: 100px; /* Adjust based on your thumbnail size */
    height: auto;
    display: block;
}

.large-image-container {
    position: absolute;
    top: 0;
    left: 110px; /* Adjust based on your thumbnail size and desired position */
    display: none;
    z-index: 1000;
}

.large-image {
    width: 300px; /* Adjust based on your large image size */
    height: auto;
    border: 1px solid #ccc;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
}

### JavaScript (script.js)


function showLargeImage(event) {
    var largeImageContainer = document.getElementById('largeImageContainer');
    var rect = event.target.getBoundingClientRect();
    largeImageContainer.style.left = (rect.left + rect.width + 10) + 'px'; // Adjust position
    largeImageContainer.style.top = rect.top + 'px'; // Adjust position if needed
    largeImageContainer.style.display = 'block';
}

function hideLargeImage() {
    document.getElementById('largeImageContainer').style.display = 'none';
}

**注意**:

- 在HTML中,`.thumbnail` 是缩略图的类名,`.large-image-container` 是包含大图的容器。当鼠标悬停在缩略图上时,`showLargeImage` 函数会被触发,显示大图;当鼠标离开时,`hideLargeImage` 函数会被触发,隐藏大图。

- CSS中`.large-image-container` 的位置是相对于`.image-container`定位的,因此`.image-container`需要设置为`position: relative;`。

- 你需要根据你的具体需求调整缩略图和大图的尺寸、位置等样式。

- 确保`small-image.jpg`和`large-image.jpg`是你实际图片的路径。