css
#drag {
300px;
height: 200px;
border: 1px dashed #ccc;
border-radius: 4px;
overflow: hidden;
}
#drag:hover {
border-color: cyan;
}
#drag.dragEnter {
border: 2px dashed cyan;
background-color: #eee;
}
#drag #view {
100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
}
#drag #view p {
color: #2f2f2f;
}
#drag #view img {
100%;
height: 100%;
object-fit: cover;
display: block;
}
html
<div id="drag">
<input type="file" id="upload" style="display: none">
<div id="view">
<p>将图片拖拽到此处</p>
</div>
</div>
javascript
const FILE_TYPES = ['jpg', 'jpeg', 'png', 'gif']
const drag = document.querySelector('#drag')
const upload = drag.querySelector('#upload')
const view = drag.querySelector('#view')
const accept = FILE_TYPES.map(v => `image/${v}`).join(',')
upload.setAttribute('accept', accept)
drag.addEventListener('dragenter', () => {
drag.classList.add('dragEnter')
})
drag.addEventListener('dragleave', () => {
drag.classList.remove('dragEnter')
})
drag.addEventListener('dragover', (e) => {
e.stopPropagation()
e.preventDefault()
})
drag.addEventListener('click', (e) => {
e.stopPropagation()
upload.click()
})
drag.addEventListener('drop', (e) => {
e.stopPropagation()
e.preventDefault()
drag.classList.remove('dragEnter')
const [file] = e.dataTransfer.files
if (!file) return
const { type = '' } = file
const [, fileType] = type.toLowerCase().split('/')
if (!FILE_TYPES.includes(fileType)) {
alert('unsupported file type')
return false
}
handleFile(file, view)
})
upload.addEventListener('click', (e) => {
e.stopPropagation()
})
upload.addEventListener('change', function (e) {
const [file] = e.target.files
if (!file) return upload.value = ''
const { type = '' } = file
const [, fileType] = type.toLowerCase().split('/')
if (!FILE_TYPES.includes(fileType)) {
upload.value = ''
alert('unsupported file type')
return false
}
handleFile(file, view)
})
function handleFile(file, container) {
const blob = URL.createObjectURL(file)
const image = new Image()
image.src = blob
container.innerHTML = ''
container.appendChild(image)
}