Image change onclick not work in mobile browser

荒凉一梦 提交于 2019-12-10 12:18:06

问题


I have a code that will change the image upon clicking on the image. However, since I am using mouseup/mousedown, is there a way to make it so that it also work in mobile browsers as well?

$(document).ready(function(){
  $(".menulink").eq(0).mouseup(function(){
        $('#menu1').attr('src', 'http://placehold.it/333/3ef/img/picture2.jpg');
  });
  $(".menulink").eq(0).mousedown(function(){
        $('#menu1').attr('src', 'http://placehold.it/333/fe3/img/picture1.jpg');
  });
  $(".menulink").eq(1).mouseup(function(){
        $('#menu2').attr('src', 'http://placehold.it/333/3ef/img/picture2.jpg');
  });
  $(".menulink").eq(1).mousedown(function(){
        $('#menu2').attr('src', 'http://placehold.it/333/fe3/img/picture1.jpg');
  });
});

Here is the fiddle page


回答1:


Yes, you need to use touchstart and touchend. I also made this slightly more efficient, hope you don't mind.

$(function(){
    var $menulink = $('.menulink'),
        $menu1 = $('#menu1'),
        $menu2 = $('#menu2');

    function setSrc($menu,$src){
        $menu.src = $src;
    }

    $menulink.eq(0).on({
        'mouseup touchstart':function(){
             setSrc($menu1[0],'http://placehold.it/333/3ef/img/picture2.jpg');
        },
        'mousedown touchend':function(){
             setSrc($menu1[0],'http://placehold.it/333/3ef/img/picture1.jpg');
        }
    });

    $menulink.eq(1).on({
        'mouseup touchstart':function(){
             setSrc($menu2[0],'http://placehold.it/333/3ef/img/picture2.jpg');
        },
        'mousedown touchend':function(){
             setSrc($menu2[0],'http://placehold.it/333/3ef/img/picture1.jpg');
        }
    });
});

This might be even more efficient, and is especially helpful if you have more than just the two.

$(function(){
    var $menulink = $('.menulink');

    for(i=$menulink.length;i--;){
        var $menu = $('#menu'+(i+1))[0];

        $menulink.eq(i).on({
            'mouseup touchstart':function(){
                 $menu.src = 'http://placehold.it/333/3ef/img/picture2.jpg';
            },
            'mousedown touchend':function(){
                 $menu.src = 'http://placehold.it/333/3ef/img/picture1.jpg';
            }
        });
    }
});

Just another option to consider.




回答2:


To add to @Jonathan's answer, also checkout https://github.com/furf/jquery-ui-touch-punch which applies the touch events to their mouse counterparts.




回答3:


Edit: don't use click

Yes, you use touchstart and touchend.



来源:https://stackoverflow.com/questions/17353009/image-change-onclick-not-work-in-mobile-browser

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