HTML+CSS+JS完成商品详细页其中要包含图片的放大和图片的轮转两种 js 实现的动态交互效,附加完整的代码
时间: 2024-03-24 08:38:07 浏览: 9
以下是一个基于 HTML、CSS 和 JavaScript 的商品详细页示例,其中包含图片的放大和图片的轮转两种动态交互效果:
```html
<!DOCTYPE html>
<html>
<head>
<title>Product Details</title>
<style>
#product-images {
display: flex;
flex-wrap: wrap;
margin-bottom: 20px;
}
#product-images img {
width: 100px;
height: 100px;
margin-right: 10px;
cursor: pointer;
border: 1px solid #ddd;
border-radius: 4px;
}
#product-main-image {
width: 400px;
height: 400px;
border: 1px solid #ddd;
border-radius: 4px;
background-color: #f2f2f2;
background-image: url("main-image.jpg");
background-repeat: no-repeat;
background-size: contain;
background-position: center;
margin-bottom: 20px;
}
#product-zoom {
position: absolute;
display: none;
width: 200px;
height: 200px;
border: 1px solid #ddd;
border-radius: 4px;
background-repeat: no-repeat;
background-size: 800px 800px;
background-position: 0 0;
z-index: 999;
}
</style>
<script>
window.addEventListener("load", function() {
var mainImage = document.getElementById("product-main-image");
var zoom = document.getElementById("product-zoom");
mainImage.addEventListener("mousemove", function(event) {
var rect = mainImage.getBoundingClientRect();
var x = event.clientX - rect.left;
var y = event.clientY - rect.top;
var zoomX = (x / mainImage.offsetWidth) * 800;
var zoomY = (y / mainImage.offsetHeight) * 800;
zoom.style.backgroundPosition = "-" + zoomX + "px -" + zoomY + "px";
zoom.style.left = (event.pageX - 100) + "px";
zoom.style.top = (event.pageY - 100) + "px";
});
var images = document.querySelectorAll("#product-images img");
for (var i = 0; i < images.length; i++) {
images[i].addEventListener("click", function() {
mainImage.style.backgroundImage = "url('" + this.src + "')";
});
}
});
</script>
</head>
<body>
<div id="product-images">
<img src="image-1.jpg">
<img src="image-2.jpg">
<img src="image-3.jpg">
<img src="image-4.jpg">
</div>
<div id="product-main-image">
<div id="product-zoom"></div>
</div>
</body>
</html>
```
该示例中,`#product-images` 是一个包含所有商品图片的容器,每个图片都是一个 `img` 元素,并且具有一个 `click` 事件监听器,用于在单击时将其设置为主要图片。主要图片是一个具有 ID 为 `product-main-image` 的 `div` 元素,它具有一个背景图像,并且具有一个 `mousemove` 事件监听器,用于在鼠标移动时显示放大的图片。放大的图片是一个具有 ID 为 `product-zoom` 的 `div` 元素,它具有一个背景图像,并且在鼠标移动时根据鼠标位置更新其背景位置。