html 开启图片预览
时间: 2023-07-06 22:34:18 浏览: 51
要在 HTML 中开启图片预览,可以使用以下步骤:
1. 在 HTML 文件中插入一张图片,例如:
```html
<img src="example.jpg" alt="Example Image">
```
2. 在 `<head>` 标签中添加以下代码:
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
```
3. 在 `<head>` 标签中添加以下 CSS 代码:
```html
<style>
.preview {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.7);
z-index: 9999;
}
.preview img {
display: block;
max-width: 80%;
max-height: 80%;
margin: auto;
margin-top: 5%;
}
</style>
```
4. 在 `<body>` 标签中添加以下 JavaScript 代码:
```html
<script>
$(document).ready(function() {
$("img").click(function() {
var src = $(this).attr("src");
$("body").append("<div class='preview'><img src='" + src + "'></div>");
$(".preview").click(function() {
$(this).remove();
});
});
});
</script>
```
这些步骤将为您的 HTML 页面添加一个简单的图片预览功能。当用户单击页面上的任何图片时,将显示一个半透明的黑色背景,图片将在其中心显示。用户可以单击预览窗口以关闭它。