创建一个简单的商品网页可以用HTML、CSS和JavaScript来实现。这种网页会包括商品的图片、名称、描述、价格和购买按钮等。下面是一个详细的源码案例及其讲解:
1. 文件结构
假设我们有以下文件结构:
/product-page/imagesproduct.jpgindex.htmlstyle.cssscript.js
2. HTML (index.html)
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>商品页面</title><link rel="stylesheet" href="style.css">
</head>
<body><div class="product-container"><div class="product-image"><img src="images/product.jpg" alt="Product Image"></div><div class="product-details"><h1 class="product-name">商品名称</h1><p class="product-description">这是一个非常好的商品,它有很多优点和特点,非常适合您。</p><span class="product-price">$99.99</span><button class="buy-button">购买</button></div></div><script src="script.js"></script>
</body>
</html>
3. CSS (style.css)
body {font-family: Arial, sans-serif;background-color: #f4f4f4;margin: 0;padding: 0;display: flex;justify-content: center;align-items: center;height: 100vh;
}.product-container {background-color: #fff;box-shadow: 0 4px 8px rgba(0,0,0,0.1);border-radius: 10px;overflow: hidden;width: 300px;text-align: center;
}.product-image img {width: 100%;height: auto;
}.product-details {padding: 15px;
}.product-name {font-size: 24px;margin: 0;
}.product-description {color: #777;font-size: 14px;margin: 10px 0;
}.product-price {font-size: 20px;color: #333;margin: 15px 0;display: block;
}.buy-button {background-color: #28a745;color: white;border: none;padding: 10px 20px;font-size: 16px;cursor: pointer;border-radius: 5px;transition: background-color 0.3s ease;
}.buy-button:hover {background-color: #218838;
}
4. JavaScript (script.js)
document.querySelector('.buy-button').addEventListener('click', function() {alert('感谢您的购买!');
});
讲解
-
HTML:
<!DOCTYPE html>
声明文档类型为HTML5。<head>
部分包括字符集、视口设置和引用CSS文件。<body>
部分包含商品的图片和详情,并引用JavaScript文件。
-
CSS:
- 设置了整体页面的样式,包括字体、背景颜色和布局。
- 为商品容器和其中的元素(如图片、名称、描述、价格、按钮)定义了具体的样式和样式效果。
-
JavaScript:
- 添加了一个点击事件监听器,当点击“购买”按钮时,弹出一个感谢信息的提示框。
这个示例展示了一个简单但功能完整的商品展示页面。可以根据具体需求扩展和调整,例如添加更多商品、实现购物车功能、连接后端API获取商品数据等。