问题描述
我正在使用onMouseOver来检测用户在通过手机访问我的Web应用程序时何时点击图片:
<img
onMouseOver={(e) => {
myImageWidget.open();
}}
/>
当他点击图像时,会出现一个小部件并可以上传图像。
使用onMouseOver
的问题在于,当在桌面浏览器上使用Web应用程序时,每当用户将鼠标悬停在图像上时,窗口小部件就会出现。
那么有没有办法在桌面浏览器上阻止这种行为,同时又将这种行为保持在手机上?
解决方法
如果您愿意依靠浏览器的User-Agent字符串,则可以使用is-mobile。注意:似乎无法可靠地检测触摸屏,请参见this thorough article.
import mobile from "is-mobile";
const isMobile = mobile(navigator.userAgent || navigator.vendor);
<img
onMouseOver={(e) => {
isMobile && myImageWidget.open();
}}
/>