Html5 ontouchstart与ontouchend

来源:互联网 发布:java web编程技术 pdf 编辑:程序博客网 时间:2024/06/01 13:01

        一开始做项目时,还是把项目(web app)当初PC端的项目来做,然后项目方面提出了一个需求说是手指触摸屏幕上的某条信息时,背景色需要切换成另外一种颜色,当手指离开时变回原来的颜色,我一想,这个好简单。。。搞个a标签用伪类hover就可以实现了,好吧,一开始想简单了,就这样弄上去了,运行项目,发现没有想要的效果。。。然后就各种检查(代码),发现没问题之后,就开始着手是不是移动端的跟PC端的有什么区别没有,最后定位到:移动端是没有鼠标事件,换言之就是用上面的方式是行不通的,好吧那看看有没有解决的方法。

        最后找到了ontouchstart与ontouchend这两个事件,问题解决,效果也实现了。实例代码如下:

<!DOCTYPE html><html>     <head>        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">       <script type="text/javascript">       window.onload = function() {    var friends = document.getElementsByClassName("friend");// 循环    for(var i = 0; i < friends.length; i++) {         (function(i) {              friends[i].ontouchstart =function() {                      this.style.backgroundColor ="red";                };                friends[i].ontouchend =function() {                     this.style.backgroundColor ="white";               };           })(i);     }     };       </script>     </head>     <body>   <div class="friend">好友A1244214214</div><br>  <div class="friend">好友B4214214</div><br>  <div class="friend">好友C4214214</div>    </body> </html>


 

0 0