Apple 宣布,通过其新款 iPhone 6S 和 6S+,用户现在可以使用压力与他们的应用程序进行交互。是否有一个 JavaScript API 可供 Web 开发人员在标准网站上利用这一新功能?如果是这样,如何实施?
问问题
1216 次
2 回答
2
是的,根据 W3C,最近在interface的规范中添加了一个新force
Touch
属性,范围从 0(最小力)到 1(最大力)。这已经可用于 iOS9 上的 Safari(不确定 Chrome 或其他浏览器是否已实现它)。
快速回答:
要访问此属性,只需调用
touchForce = evt.originalEvent.touches[0].force;
在一个touchstart
或touchmove
事件监听器中。
这个实现有几个问题:
- 在 上
touchstart
,力将非常接近于 0,因为一旦检测到压力的第一个迹象就会调用它。 touchstart
如果压力增加或减少,该事件将不会再次触发。touchmove
不可靠,因为您必须等待位置更改才能force
读取新内容,但情况并非总是如此。
解决方案:
为了解决这个问题,您可以设置一个超时,每隔几毫秒评估一次这个力touchstart
,然后清除超时touchend
。
var tO = 0;
$("#div1").on("touchstart", startTouch);
$("#div1").on("touchend", endTouch);
function startTouch(evt){
evt.preventDefault();
touchForce = evt.originalEvent.touches[0].force;
tO = window.setTimeout(function(){startTouch(evt)}, 100);
// Do something with touchForce
}
function endTouch(){
touchForce = 0;
window.clearTimeout(tO);
// Do something else
}
这有点hacky,但它有效。也许将来他们会创建一个新forcechange
活动,但这就是我们现在所拥有的。
请原谅 JQuery,我用它来更快地说明这一点。
于 2015-12-01T21:13:56.300 回答
0
您可以使用 JS 库Pressure.js。如果您有 iPhone 6s 或带有新 Force Touch 触控板的新 Macbook,那么在 iOS 和 OSX 上获取 Force 和 3D Touch 值真的很容易。
语法也很简单,这里有一个例子:
Pressure.set('#element', {
start: function(){
// this is called on force start
},
end: function(){
// this is called on force end
},
startDeepPress: function(){
// this is called on "force click" / "deep press", aka once the force is greater than 0.5
},
endDeepPress: function(){
// this is called when the "force click" / "deep press" end
},
change: function(force, event){
// this is called every time there is a change in pressure
// here the 'force' variable passed in container the current pressure force
},
unsupported: function(){
// this is called once there is a touch on the element and the device or browser does not support Force or 3D touch
}
});
于 2016-01-28T21:38:54.627 回答