Latest Post

Tăng thứ hạng và truy cập tự nhiên với 10 phương pháp SEO hay nhất Kiếm Tiền Online (mmo): Khái Niệm và Các Hình Thức Phổ Biến

Các thông tin khi chúng ta sao chép sẽ được lưu vào clipboard của hệ điều hành. Sử dụng Clipboard API của JavaScript giúp chúng ta truy cập thông tin từ clipboard. Trong hướng dẫn này, chúng ta sẽ thực hiện việc trích xuất thông tin ảnh từ clipboard và nhúng nó vào một tài liệu HTML.

Truy xuất dữ liệu từ clipboard trong Javascript

Đây là đoạn mã sử dụng Clipboard API đẻ lấy dữ liệu.

<script type="text/javascript">
    document.onpaste = function(pasteEvent) {
        // consider the first item (can be easily extended for multiple items)
        var item = pasteEvent.clipboardData.items[0];

        if (item.type.indexOf("image") === 0)
        {
            var blob = item.getAsFile();
            var reader = new FileReader();
            reader.onload = function(event) {
                document.getElementById("container").src = event.target.result;
            };
            reader.readAsDataURL(blob);
        }
    }
</script>

Nó sẽ lưu dữ liệu từ clipboard vào element có ID là “container”

Và đoạn HTML để hiển thị dữ liệu từ clipboard là:

<p>Paste your image here…</p>
<img id="container"/>

Kết quả:

Đoạn code cuối cùng là:

<html>
<head>
    <title>Tutorial from vinasupport.com</title>
    <script type="text/javascript">
        document.onpaste = function(pasteEvent) {
            // consider the first item (can be easily extended for multiple items)
            var item = pasteEvent.clipboardData.items[0];

            if (item.type.indexOf("image") === 0)
            {
                var blob = item.getAsFile();
                var reader = new FileReader();
                reader.onload = function(event) {
                    document.getElementById("container").src = event.target.result;
                };
                reader.readAsDataURL(blob);
            }
        }
    </script>
</head>
<body>
    <p>Paste your image here…</p>
    <img id="container"/>
</body>
</html>

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *