Why does my close button not work on touchscreens?

2019-08-07 09:46发布

I got a close button that only shows up when an image is clicked, the image will be resized and after clicking the close button it will be resized to its origin size. Works fine on PCs but not on mobile devices. Here is the code:

$(document).ready(function () {
   $('.image').click(function (event) {
       /* code for hiding some elements and enlarging the image here */
       $('#close_button2').show();
   });
   $('#close_button2').on('touchend click', function(event){
       /* code for showing some elements and display the image in the smaller size again */
       $('#close_button2').hide();
   });
   $(document).keyup(function (e) {
            if (e.keyCode == 27) {
                /* some code for pressing escape button */
            }
   });
});

Instead of $('#close_button2').on('touchend click', function(event){ I also tried:

$('#close_button2').click(function (event) {
$('#close_button2').on( "vclick", function( event ) { //jQuery mobile only - there were some conflicts with my code
$('#close_button2').on(isMobile ? 'touchend' : 'click', function(event) {
$(document).on('click', '#close_button2', function(event) {

But nothing worked. Any ideas?

1条回答
Deceive 欺骗
2楼-- · 2019-08-07 10:36

on does not appear to like multiple events (surprised me too!).

Use bind instead:

JSFiddle: http://jsfiddle.net/TrueBlueAussie/TWDZY/

$(document).ready(function () {
   $('.image').click(function (event) {
       /* code for hiding some elements and enlarging the image here */
       $('#close_button2').show();
   });
   $('#close_button2').bind('touchend click', function(event){
       /* code for showing some elements and display the image in the smaller size again */
       $('#close_button2').hide();
   });
   $(document).keyup(function (e) {
            if (e.keyCode == 27) {
                /* some code for pressing escape button */
            }
   });
});
查看更多
登录 后发表回答