问题
I created a form on a website that allows users to upload files. Users can also drag and drop files onto this form. However, on some devices, it is simply not possible to drag and drop files (e.g. on my iPhone). So I only want to display the text "Drag and drop files here" only on devices on which it makes sense.
Is there a way to detect whether the device supports drag and drop files in principle? A workaround could be to detect if a mouse pointer is moving. In this case, I would guess it is possible to drag and drop files. However, it would only be a guess.
Is there a more suitable way to detect this? Please note that I don't want to detect if the browser supports drag and drop in general, but if the browser supports drag and drop files.
回答1:
You could use window.navigator.userAgent in order to detect what OS the user is using. userAgent returns a string and you could parse through the string to try and detect certain keywords inside of it. I looked at this article at geeks for geeks. Along with this stackoverflow answer here. by combining the two you should be able to pick out certain keywords and detect what the user is on for most cases. It seems that older phones might have an issue with this so it may not be perfect.
if (navigator.appVersion.indexOf("Mac") != -1) {
onWeb = true;
}
if (navigator.appVersion.indexOf("Win") != -1) {
onWeb = true;
} else {
onWeb = false;
}
In my personal opinion (please take this with a grain of salt) the amount of work involved in this with the potential errors on older devices isn't worth the work involved. Because of this I would try to use text to inform the user of the Drag and Drop potential as well as giving them a button to upload files. Some users prefer the ability to manually upload files over a drag and drop (myself), and by having both options readily available it allows users to utilize which ever choice they prefer most.
来源:https://stackoverflow.com/questions/65342745/is-there-a-way-in-javascript-to-detect-if-files-can-be-dropped-on-the-used-devic