简体   繁体   English

使用Java检查触摸设备

[英]Check for Touch device with Javascript

I have 3 buttons with hover states which makes a little tooltip appear to describe the button. 我有3个具有悬停状态的按钮,这会显示一些工具提示来描述按钮。 They work fine but on touchs screen they do not disappear after the user clicks on the button. 它们工作正常,但在触摸屏上,用户单击按钮后它们不会消失。

So I've tried a few js scripts for checking if a device is a touch device or not. 因此,我尝试了一些js脚本来检查设备是否为触摸设备。 They almost work but they also when I test on IE11 it also gets detected as a touch device. 它们几乎可以工作,但是当我在IE11上进行测试时,它们也被检测为触摸设备。 Chrome & Firefox do not get mistaken as a touch device. Chrome和Firefox不会误认为是触摸设备。

Any sugestions? 有任何建议吗?

Her is what I've tried 她是我尝试过的

/*****************************
 TOUCH DEVICES HOVER FIX START
 ****************************/
// http://stackoverflow.com/a/4819886/1814446
function isTouchDevice() {
    return 'ontouchstart' in window // works on most browsers
        || 'onmsgesturechange' in window; // works on ie10
};

// http://www.stucox.com/blog/you-cant-detect-a-touchscreen/#poke-it
var hasTouch;
window.addEventListener('touchstart', function setHasTouch () {
    hasTouch = true;
    // Remove event listener once fired, otherwise it'll kill scrolling
    // performance
    window.removeEventListener('touchstart', setHasTouch);
}, false);

// https://github.com/Modernizr/Modernizr/blob/master/feature-detects/touchevents.js
define(['Modernizr', 'prefixes', 'testStyles'], function( Modernizr, prefixes, testStyles ) {
    // Chrome (desktop) used to lie about its support on this, but that has since been rectified: http://crbug.com/36415
    Modernizr.addTest('touchevents', function() {
        var bool;
        if(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) {
            bool = true;
        } else {
            var query = ['@media (',prefixes.join('touch-enabled),('),'heartz',')','{#modernizr{top:9px;position:absolute}}'].join('');
            testStyles(query, function( node ) {
                bool = node.offsetTop === 9;
            });
        }
        return bool;
    });
});

if(bool===true) {
    console.log('Touch Device'); //your logic for touch device
    jQ( "#btn-1, #btn-2, #btn-3" ).click(function() {
        jQ("#btn-1 .tooltip").css('opacity', '0');
        jQ("#btn-2 .tooltip").css('opacity', '0');
        jQ("#btn-3 .tooltip").css('opacity', '0');
    });
}
else {
    //your logic for non touch device
}

For IE10+ you can utilize "window.navigator.msMaxTouchPoints" 对于IE10 +,您可以使用“ window.navigator.msMaxTouchPoints”

example code 示例代码

function isIETouch ()
{
return window.navigator.msMaxTouchPoints == undefined ? false : window.navigator.msMaxTouchPoints;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM