问题描述

$(document).on("touchstart touchmove",".btn-highlight",function(event){
        $(this).addClass("hover");
    }).on("touchend touchcancel",".btn-highlight",function(event){
        $(this).removeClass("hover");
    });

起初想用这一段代码来模拟部分按钮的高光效果(就是点击一个按钮之后会有个不同的样式,类似PC的hover)

但是发现一个问题,就是在安卓手机上,下面的这个方法却经常不触发,非常的偶尔,着实令吾等烦恼。

 

后经查阅资料发现浏览器的默认事件影响了我们这个事件的触发。那么就涉及阻止默认事件了,很简单,加上event.preventDefault();

最终可用代码为

$(document).on("touchstart touchmove",".btn-highlight",function(event){
        $(this).addClass("hover");
        event.preventDefault();
    }).on("touchend touchcancel",".btn-highlight",function(event){
        $(this).removeClass("hover");
    });

在css里面对.btn-highlight加上对应的样式就可以看到效果了,如按钮a与按钮b想显示不同的效果,那么

先给a和b都加上.btn-highlight

CSS中:

a.hover{/*第一种样式*/}

b.hover{/*第二种样式*/}

 

该问题续集~~~

发现这样写之后,如果那个按钮是链接呢???跳转不了,因为禁用默认事件了,现在把touchstart和touchmove分开写就OK了

$(document).on("touchstart",".btn-highlight",function(){
        $(this).addClass("hover");
    }).on("touchmove",".btn-highlight",function(event){
        event.preventDefault();
    }).on("touchcancel touchend",".btn-highlight",function(event){
        $(this).removeClass("hover");
    });

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-01-01
  • 2021-06-22
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-06-03
  • 2022-02-12
  • 2022-02-11
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案