Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

html图片预览控件

作者:狂拽今生   发布日期:2026-06-26   浏览:108

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTML 图片预览控件</title>
    <style>
        .preview-container {
            width: 300px;
            height: 300px;
            border: 1px solid #ccc;
            margin-top: 10px;
            overflow: hidden;
        }
        .preview-container img {
            max-width: 100%;
            max-height: 100%;
        }
    </style>
</head>
<body>
    <h1>图片预览控件示例</h1>
    <input type="file" id="imageInput" accept="image/*">
    <div class="preview-container" id="previewContainer"></div>

    <script>
        document.getElementById('imageInput').addEventListener('change', function(event) {
            const file = event.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    const img = document.createElement('img');
                    img.src = e.target.result;
                    document.getElementById('previewContainer').innerHTML = ''; // 清空之前的预览
                    document.getElementById('previewContainer').appendChild(img);
                };
                reader.readAsDataURL(file);
            }
        });
    </script>
</body>
</html>

解释说明:

  1. HTML 结构:

    • input 元素用于选择图片文件,accept="image/*" 限制只能选择图片文件。
    • div 元素用于显示图片预览,类名为 preview-container
  2. CSS 样式:

    • .preview-container 设置了固定宽度和高度,并添加了边框,确保图片在容器内显示。
    • .preview-container img 确保图片不会超出容器的大小。
  3. JavaScript 功能:

    • 监听 input 元素的 change 事件,当用户选择图片时触发。
    • 使用 FileReader 对象读取选中的图片文件,并将其转换为 Data URL。
    • 创建一个新的 img 元素,设置其 src 属性为读取到的 Data URL,然后将其添加到预览容器中。

上一篇:html 在线预览

下一篇:html动画特效代码

大家都在看

静态html源码

404 html

ios打开html

用于定义html文档所要显示内容的是

html创建表格

nginx访问不到html

html 符号

colspan在html中是什么意思

html iframe嵌套页面

怎么将网页另存为html

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站