前端頁面實現聊天粘貼圖片功能

項目需求:客服聊天系統須要可粘貼圖片發送功能;html

html頁面:htm

設置一個可編輯的div圖片

<div id="editor" class="texter" tabindex="0" contenteditable="true" onpaste="return pasteListener(event, true)"></div>ip

jq代碼:get

function pasteListener(event, isLimit) {
  $.each(event.clipboardData.items, function(index, item) {
    if(item.kind == "file" && item.type.match("image/*")) {
      var file = item.getAsFile();
      if(isLimit && file.size > 2 * 1024 * 1024) {
        parent.index.layers("msg", "粘貼的圖片內容過大,最大支持爲2M。");
        return true;
      }
      var fileReader = new FileReader();
      fileReader.onload = function(event) {
        var img = "<img src='" + event.target.result + "' style='" + (isLimit ? "width:200px;" : "") + "'" + (isLimit ? "" : "") + ">";
        var selection = window.getSelection();
        var range = selection.getRangeAt(0);
        range.insertNode($(img)[0]);
        selection.anchorOffset = selection.focusOffset;
        selection.collapseToEnd();
      }
      fileReader.readAsDataURL(file);
     } else if(item.kind == "string" && item.type.match("text/plain")) {
        item.getAsString(function(str) {
          var selection = window.getSelection();
          var range = selection.getRangeAt(0);
          range.insertNode(new Text(str));
          selection.anchorOffset = selection.focusOffset;
          selection.collapseToEnd();
       });
    }
  });
  return false;
}string

相關文章
相關標籤/搜索