源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

移动端点击态处理的三种实现方式

  • 时间:2022-04-25 19:53 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:移动端点击态处理的三种实现方式
[b]前言[/b] 在开发移动端页面的时候,为了提高用户体验,通常会给被触控的元素加上一个效果来对用户的操作进行反馈。这种反馈主要有三种实现方式,有需要的朋友们下面来一起看看吧。 [b]一、伪类:active [/b] :active伪类常用于设定点击状态下或其他被激活状态下一个链接的样式。最常用于锚点<a href="#">这种情况,一般主流浏览器下也支持其他元素,如button等。在多按键的鼠标系统中,:active只适用于主按键,目前的大部分情况都是左键即主键。 该伪类下定义的CSS样式只在按下鼠标按钮与释放鼠标按钮之间的短暂瞬间被触发显示。使用键盘的tab键也可以触发:active状态。 [b]值得注意的是:[/b]伪类是一种比较方便的实现方式,但在ios中,需要在相关的元素或者[code]body[/code]上绑定[code]touchstart[/code]事件才能使元素的[code]:active[/code]生效。
By default, Safari Mobile does not use the :active state unless there is a touchstart event handler on the relevant element or on the .—MDN
document.body.addEventListener('touchstart', function (){});
也可以直接在[code]body[/code]上添加
<body touchstart>
 <!-- ... -->
</body>
此外,由于移动端300ms延迟问题,触摸反馈会有延迟,可以使用Fastclick解决。 [b]二、webkit-tap-highlight-color [/b] 这个属性并不是标准的,被用于设置超链接被点击时高亮的颜色,在ios设备上表现为一个半透膜的灰色背景,可以设置[code]-webkit-tap-highlight-color[/code]为任何颜色,例如[code]rgba(0,0,0,0.5) [/code],如果未设置颜色的[code]alpha[/code]值,将使用默认的透明度,[code]alpha[/code]为0时,将禁用高亮,[code]alpha[/code]为1时,元素在点击时将不可见 大部分安卓设备也支持这个属性,但是显示的效果不同,表现为一个边框, [code]-webkit-tap-highlight-color[/code]的值为边框的颜色 [b]三、touch事件 [/b] 当用户手指放在移动设备在屏幕上滑动会触发的touch事件。原理就是[code]touchstart[/code]时,给元素添加[code]className[/code],[code]touchstend[/code]时移除[code]className[/code]
<!-- 省略 -->
<li data-touch="true">
点我
</li>
<!-- 省略 -->
<script>
 document.body.addEventListener('touchstart', function(e){
 var target = e.target
 if(target.dataset.touch === 'true'){
  target.classList.add('active')
 }
 })
 document.body.addEventListener('touchmove', function(e){
 var target = e.target,
  rect = target.getBoundingClientRect()
 if(target.dataset.touch === 'true'){
  // 移出元素时,取消active状态
  if(e.changedTouches[0].pageX<rect.left || e.changedTouches[0].pageX>rect.right || e.changedTouches[0].pageY<rect.top || e.changedTouches[0].pageY>rect.bottom){
  target.classList.remove('active')
  }
 }
 })
 document.body.addEventListener('touchcancel', function(e){
 var target = e.target
 if(target.dataset.touch === 'true'){
  target.classList.remove('active')
 }
 })
 document.body.addEventListener('touchend', function(e){
 var target = e.target
 if(target.dataset.touch === 'true'){
  target.classList.remove('active')
 }
 })
</script>
[b]总结[/b] 以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部