什么';这是检测';触摸屏&x27;使用JavaScript的设备?
我已经编写了一个jQuery插件,可以在桌面和移动设备上使用。我想知道是否有一种JavaScript方法可以检测设备是否具有触摸屏功能。我使用jquery-mobile.js来检测触摸屏事件,它可以在iOS、Android等平台上运行,但我还想根据用户的设备是否有触摸屏来编写条件语句什么';这是检测';触摸屏&x27;使用JavaScript的设备?,javascript,jquery,touch,Javascript,Jquery,Touch,我已经编写了一个jQuery插件,可以在桌面和移动设备上使用。我想知道是否有一种JavaScript方法可以检测设备是否具有触摸屏功能。我使用jquery-mobile.js来检测触摸屏事件,它可以在iOS、Android等平台上运行,但我还想根据用户的设备是否有触摸屏来编写条件语句 这可能吗?更新2021 要查看旧答案,请查看历史记录。我决定从头开始,因为当我把历史记录保留在帖子里的时候,它已经失控了 我最初的回答是,使用与Modernizer相同的功能可能是个好主意,但这不再有效,因为他们删
这可能吗?更新2021 要查看旧答案,请查看历史记录。我决定从头开始,因为当我把历史记录保留在帖子里的时候,它已经失控了 我最初的回答是,使用与Modernizer相同的功能可能是个好主意,但这不再有效,因为他们删除了此PR上的“touchevents”测试:因为这是一个令人困惑的主题 话虽如此,这应该是检测浏览器是否具有“触摸功能”的一种相当不错的方法:
函数istouch device(){
返回((窗口中的“ontouchstart”)||
(navigator.maxTouchPoints>0)||
(navigator.msmax触点>0));
}
但是对于比我更聪明的人写的更高级的用例,我建议阅读以下文章:
html.touch div {
width: 480px;
}
html.no-touch div {
width: auto;
}
和Javascript(jQuery示例):
或
var isTouchScreen='createTouch'在文档| | screen.width检查一下,它提供了一个非常好的代码片段,用于在检测到触摸设备时执行什么操作,或者在调用touchstart事件时执行什么操作:
$(function(){
if(window.Touch) {
touch_detect.auto_detected();
} else {
document.ontouchstart = touch_detect.surface;
}
}); // End loaded jQuery
var touch_detect = {
auto_detected: function(event){
/* add everything you want to do onLoad here (eg. activating hover controls) */
alert('this was auto detected');
activateTouchArea();
},
surface: function(event){
/* add everything you want to do ontouchstart here (eg. drag & drop) - you can fire this in both places */
alert('this was detected by touching');
activateTouchArea();
}
}; // touch_detect
function activateTouchArea(){
/* make sure our screen doesn't scroll when we move the "touchable area" */
var element = document.getElementById('element_id');
element.addEventListener("touchstart", touchStart, false);
}
function touchStart(event) {
/* modularize preventing the default behavior so we can use it again */
event.preventDefault();
}
我使用上面的代码片段来检测触摸是否正常,所以我的fancybox iframes会显示在桌面电脑上,而不是触摸屏上。我注意到Opera Mini for Android 4.0在单独使用blmstr代码时仍然注册为非触摸设备。(有人知道为什么吗?)
我最终使用了:
<script>
$(document).ready(function() {
var ua = navigator.userAgent;
function is_touch_device() {
try {
document.createEvent("TouchEvent");
return true;
} catch (e) {
return false;
}
}
if ((is_touch_device()) || ua.match(/(iPhone|iPod|iPad)/)
|| ua.match(/BlackBerry/) || ua.match(/Android/)) {
// Touch browser
} else {
// Lightbox code
}
});
</script>
$(文档).ready(函数(){
var ua=navigator.userAgent;
函数为\u touch\u device(){
试试{
document.createEvent(“TouchEvent”);
返回true;
}第(e)款{
返回false;
}
}
如果((是触摸设备())| ua.match(/(iPhone | iPod | iPad)/)
||ua.match(/BlackBerry/)| ua.match(/Android/){
//触摸浏览器
}否则{
//灯箱代码
}
});
我使用:
if(jQuery.support.touch){
alert('Touch enabled');
}
在jQuery mobile 1.0.1中,我喜欢这个:
function isTouchDevice(){
return typeof window.ontouchstart !== 'undefined';
}
alert(isTouchDevice());
由于Modernizr在Windows Phone 8/WinRT上未检测到IE10,一个简单的跨浏览器解决方案是:
var supportsTouch = 'ontouchstart' in window || navigator.msMaxTouchPoints;
您只需检查一次,因为设备不会突然支持或不支持触摸,所以只需将其存储在变量中,这样您就可以更高效地多次使用它。我将避免使用屏幕宽度来确定设备是否为触摸设备。有比699px大得多的触摸屏,想想Windows8。Navigatior.userAgent可以很好地覆盖错误的帖子
我建议你去看看Modernizer
是否要测试该设备是否支持触摸事件或是触摸设备。不幸的是,这不是一回事。看起来Chrome 24现在支持触摸事件,可能是针对Windows 8。因此,这里发布的代码不再有效。我不再尝试检测浏览器是否支持触摸,而是绑定触摸和单击事件,并确保只调用一个:
myCustomBind = function(controlName, callback) {
$(controlName).bind('touchend click', function(e) {
e.stopPropagation();
e.preventDefault();
callback.call();
});
};
然后称之为:
myCustomBind('#mnuRealtime', function () { ... });
希望这有帮助 使用上面的所有注释,我汇编了以下代码,这些代码符合我的需要:
var isTouch = (('ontouchstart' in window) || (navigator.msMaxTouchPoints > 0));
我已经在iPad、Android(浏览器和Chrome)、黑莓Playbook、iPhone4S、WindowsPhone8、IE10、IE8、IE10(带触摸屏的Windows8)、Opera、Chrome和Firefox上进行了测试
它目前在WindowsPhone7上失败,我还没有找到一个解决方案
希望有人觉得这很有用。如果您使用,它很容易使用modernizer.touch
,如前所述
但是,为了安全起见,我更喜欢结合使用modernizer.touch
和用户代理测试
var deviceAgent = navigator.userAgent.toLowerCase();
var isTouchDevice = Modernizr.touch ||
(deviceAgent.match(/(iphone|ipod|ipad)/) ||
deviceAgent.match(/(android)/) ||
deviceAgent.match(/(iemobile)/) ||
deviceAgent.match(/iphone/i) ||
deviceAgent.match(/ipad/i) ||
deviceAgent.match(/ipod/i) ||
deviceAgent.match(/blackberry/i) ||
deviceAgent.match(/bada/i));
if (isTouchDevice) {
//Do something touchy
} else {
//Can't touch this
}
如果不使用Modernizer,只需将上面的Modernizer.touch
功能替换为(“document.documentElement”中的“ontouchstart”)
还请注意,测试用户代理iemobile
将为您提供比Windows Phone
更大范围的检测到的Microsoft移动设备
这一款即使在Windows Surface平板电脑中也能正常工作
function detectTouchSupport {
msGesture = window.navigator && window.navigator.msPointerEnabled && window.MSGesture,
touchSupport = (( "ontouchstart" in window ) || msGesture || window.DocumentTouch && document instanceof DocumentTouch);
if(touchSupport) {
$("html").addClass("ci_touch");
}
else {
$("html").addClass("ci_no_touch");
}
}
扩展jQuery支持
对象:
jQuery.support.touch = 'ontouchend' in document;
现在,您可以在任何地方查看它,如下所示:
if( jQuery.support.touch )
// do touch stuff
除Firefox for desktop外,支持所有浏览器始终TRUE,因为Firefox for desktop支持响应式开发人员设计,无论您是否单击触摸按钮
我希望Mozilla能在下一个版本中解决这个问题
我正在使用Firefox28桌面
function isTouch()
{
return !!("ontouchstart" in window) || !!(navigator.msMaxTouchPoints);
}
对于如何在Javascript中检测页面是否显示在触摸屏设备上,我还遇到了很多不同的选项。
国际海事组织(IMO)表示,截至目前,还不存在能够正确检测期权的实物期权。
浏览器要么报告桌面计算机上的触摸事件(因为操作系统可能已经准备好触摸),要么某些解决方案无法在所有移动设备上运行
最后,我意识到我从一开始就采取了错误的方法:
如果我的页面在触摸和非触摸设备上看起来相似,我可能根本不必担心检测属性:
我的方案是停用工具提示
jQuery.support.touch = 'ontouchend' in document;
if( jQuery.support.touch )
// do touch stuff
function isTouch()
{
return !!("ontouchstart" in window) || !!(navigator.msMaxTouchPoints);
}
function isTouchDevice(){
if(Modernizr.hasEvent('touchstart') || navigator.userAgent.search(/Touch/i) != -1){
alert("is touch");
return true;
}else{
alert("is not touch");
return false;
}
}
var isTouch = true;
window.addEventListener('mousemove', function mouseMoveDetector() {
isTouch = false;
window.removeEventListener('mousemove', mouseMoveDetector);
});
function isTouchDevice(){
return true == ("ontouchstart" in window || window.DocumentTouch && document instanceof DocumentTouch);
}
if(isTouchDevice()===true) {
alert('Touch Device'); //your logic for touch device
}
else {
alert('Not a Touch Device'); //your logic for non touch device
}
function isTouchDevice() {
return !!window.ontouchstart;
}
console.log(isTouchDevice());
if (window.addEventListener) {
var once = false;
window.addEventListener('touchstart', function(){
if (!once) {
once = true;
// Do what you need for touch-screens only
}
});
}
$('#istouch').val(1); // <-- value will be submitted with login form
if (window.addEventListener) {
window.addEventListener('mousemove', function mouseMoveListener(){
// Update hidden input value to false, and stop listening
$('#istouch').val(0);
window.removeEventListener('mousemove', mouseMoveListener);
});
}
$(document).ready(function() {
//The page is "ready" and the document can be manipulated.
if (('ontouchstart' in window) || (navigator.maxTouchPoints > 0) || (navigator.msMaxTouchPoints > 0))
{
//If the device is a touch capable device, then...
$(document).on("touchstart", "a", function() {
//Do something on tap.
});
}
else
{
null;
}
});
/* unvisited link */
a:link
{
}
/* visited link */
a:visited
{
}
/* mouse over link */
a:hover
{
}
/* selected link */
a:active
{
}
document.addEventListener('touchstart', functionref, false) // on user tap, "touchstart" fires first
document.addEventListener('mouseover', functionref, false) // followed by mouse event, ie: "mouseover"
;(function(){
var isTouch = false //var to indicate current input type (is touch versus no touch)
var isTouchTimer
var curRootClass = '' //var indicating current document root class ("can-touch" or "")
function addtouchclass(e){
clearTimeout(isTouchTimer)
isTouch = true
if (curRootClass != 'can-touch'){ //add "can-touch' class if it's not already present
curRootClass = 'can-touch'
document.documentElement.classList.add(curRootClass)
}
isTouchTimer = setTimeout(function(){isTouch = false}, 500) //maintain "istouch" state for 500ms so removetouchclass doesn't get fired immediately following a touch event
}
function removetouchclass(e){
if (!isTouch && curRootClass == 'can-touch'){ //remove 'can-touch' class if not triggered by a touch event and class is present
isTouch = false
curRootClass = ''
document.documentElement.classList.remove('can-touch')
}
}
document.addEventListener('touchstart', addtouchclass, false) //this event only gets called when input type is touch
document.addEventListener('mouseover', removetouchclass, false) //this event gets called when input type is everything from touch to mouse/ trackpad
})();
const supportsTouch = 'ontouchstart' in window;
let isUsingTouch = false;
// `touchstart`, `pointerdown`
const touchHandler = () => {
isUsingTouch = true;
document.addEventListener('mousemove', mousemoveHandler);
};
// use a simple closure to store previous time as internal state
const mousemoveHandler = (() => {
let time;
return () => {
const now = performance.now();
if (now - time < 20) {
isUsingTouch = false;
document.removeEventListener('mousemove', mousemoveHandler);
}
time = now;
}
})();
// add listeners
if (supportsTouch) {
document.addEventListener('touchstart', touchHandler);
} else if (navigator.maxTouchPoints || navigator.msMaxTouchPoints) {
document.addEventListener('pointerdown', touchHandler);
}
if(window.matchMedia("(pointer: coarse)").matches) {
// touchscreen
}
var isTouchDevice =
(('ontouchstart' in window) ||
(navigator.maxTouchPoints > 0) ||
(navigator.msMaxTouchPoints > 0));
if(!isTouchDevice){
/* Code for touch device /*
}else{
/* Code for non touch device */
}
const isTouchDevice = () => {
const prefixes = ['', '-webkit-', '-moz-', '-o-', '-ms-', ''];
const mq = query => window.matchMedia(query).matches;
if (
'ontouchstart' in window ||
(window.DocumentTouch && document instanceof DocumentTouch)
) {
return true;
}
return mq(['(', prefixes.join('touch-enabled),('), 'heartz', ')'].join(''));
};