# 拖拽

  • 阻止浏览器默认行为
$(function(){
    //阻止浏览器默认行。
    $(document).on({
        dragleave:function(e){    //拖离
            e.preventDefault();
        },
        drop:function(e){  //拖后放
            e.preventDefault();
        },
        dragenter:function(e){    //拖进
            e.preventDefault();
        },
        dragover:function(e){    //拖来拖去
            e.preventDefault();
        }
    });
    ...
});
  • 获取fileList
$document.on('change', '[name=thumb]', function (event) {
  var target = event.target
  var file = target.files[0]
  if (!file) {
    return
  }
  if (!/image/i.test(file.type)) {
    alert('请选择正确的图片格式')
    $document.find('.vi_preview p:nth-of-type(2)').text('点击 / 拖拽上传')
    $document.find('.vi_preview').removeClass('active')
    return
  }
  upload_img = file
  var thumb = URL.createObjectURL(file)
  var $preview = $('<div class="vi_preview"><img src="' + thumb + '" /></div>')
  $(target).closest('.form_group').find('.vi_preview').remove()
  $(target).before($preview)
})
  • 清空 input[type=file]
// 方案一
function resetFormElement(e) {
  e.wrap('<form>').closest('form').get(0).reset();
  e.unwrap();

  // Prevent form submission
  e.stopPropagation();
  e.preventDefault();
}

// 方案二
var control = $("#control");

$("#clear").on("click", function () {
    control.replaceWith( control = control.clone( true ) );
});
  • 通过formData 上传文件
var formData = new FormData();
formData.append('file', $('#file')[0].files[0]);
$.ajax({
    url: '/upload',
    type: 'POST',
    cache: false,
    data: formData,
    processData: false,
    contentType: false
}).done(function(res) {
}).fail(function(res) {});
  • 获取拖放文件
$('#div').on(
    'drop',
    function(e){
        if(e.originalEvent.dataTransfer){
            if(e.originalEvent.dataTransfer.files.length) {
                e.preventDefault();
                e.stopPropagation();
                /*UPLOAD FILES HERE*/
                upload(e.originalEvent.dataTransfer.files);
            }   
        }
    }
);

# 其他技巧

  • 防止拖拽选择
<div onselectstart="return false">

# 获取光标位置插入图片

var img_node = document.createElement('img')

img_node.src = img_url

$my_editor.find('.my_editor pre').focus()

if (window.getSelection) {
  var selection = window.getSelection()
  var		range = selection.getRangeAt(0)

  range.deleteContents()
  range.insertNode(img_node)
  range.collapse(false)

  selection.removeAllRanges()
  selection.addRange(range)
} else {
  console.log('insertImg: 浏览器不兼容 window.getSelection')
}

# 参考资料

Last Updated: 5/14/2022, 11:38:45 AM