Javascript onClick for mobile devices

只愿长相守 提交于 2020-01-04 02:53:13

问题


I am working on a submenu for a nav that I need to be accessible for mobile and tablet devices. I am aware that using onClick="return true" will do the trick, however, I also need my list item to close when the user clicks on the list item. Basically I need it to toggle the submenu. If I add this simple line of Javascript, it will work but the submenu will always remain open. How can I get it to close/toggle the submenu?

HTML:
        <nav>
            <ul>
                <li class="active"><a href="#">Menu 1</a></li>
                <li><a href="#">Menu 2</a></li>
                <li><a href="#">Menu 3</a></li>
                <li class="bg"><a class="dropdown" href="#">Menu 4</a>
                    <ul>
                        <li><a href="#">Sub 1</a></li>
                        <li><a href="#">Sub 2</a></li>
                    </ul>
                </li>
            </ul>
        </nav>

Javascript:
$('nav li.bg').on('click', function(){
  return true;
}

回答1:


You can use touchstart event which fires on mobile browsers.

$('nav li.bg').on('click touchstart', function(){
    return true;
});

More touch based events




回答2:


A virtual method for p click:

$('p').on("touchstart",p_touch_start);
$('p').on("touchmove",p_touch_move);
$('p').on("touchend",p_touch_end);

function p_touch_start(){
    p_touch_move.cancel_click = false;
}
function p_touch_end(){
    if(p_touch_move.cancel_click) return;
    p_touch_move.cancel_click = true;//avoid somehow repeat call
    //trigger onclick()

}
function p_touch_move(){
    //user is drag page, not click
    p_touch_move.cancel_click = true;
}



回答3:


I figured out the issue after some researching and help. Here is what was updated in my code to trigger this on mobile devices correctly after some updating of my CSS as well:

     function is_touch_device() {

     return (('ontouchstart' in window) || (navigator.MaxTouchPoints > 0) || (navigator.msMaxTouchPoints > 0));
  }

  if(is_touch_device()) {

    $('.bg').on('click', function(){

      $(this).toggleClass('activate');

      $(this).find('ul').slideToggle();
      return false;
    });
  }


来源:https://stackoverflow.com/questions/26453151/javascript-onclick-for-mobile-devices

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!