根据宽度切换点击和悬停事件 [英] Switch click and hover events based on width

查看:62
本文介绍了根据宽度切换点击和悬停事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据宽度切换事件.对于移动设备,仅单击事件应起作用.对于桌面悬停事件应该起作用.当页面加载我的代码正常工作时,我的代码大小无法正常工作. 请帮助我为什么我的代码无法正常工作.预先感谢

I want to toggle events based on width. for mobile only click event should work. for desktop hover event should work. while page loading my code working properly when resize my code is not working. please help me why my code is not working. Thanks in advance

$(document).ready(function(){

    function forDesktop(){
    $(".popover-controls div").off('click');
    $(".popover-controls div").on('hover'); 
        $(".popover-controls div ").hover(function(e){
            //popup show code
        }); 

    }
    function forMobile(){
    console.log("mobile");
    $(".popover-controls div").off('hover');
    $(".popover-controls div").on('click');

     $(".popover-controls div").click(function(e){
            //popop show

        });
    }

    function process(){ 
        $(window).width() > 600?forDesktop():forMobile();
    }
    $(window).resize(function(){
        process()
    });
    process();
});

推荐答案

非常简单,第一,您不能为每个事件编写这么多的代码.我们必须提出一个非常简单的解决方案,这是它的工作原理

Its very simple, 1st you cant write this much of code for every event. We have to come up with very simple solution, here is how it works

首先检查JS中页面的宽度,然后在主体上分配Desktop/Mobile类:

1st check the width of the Page in JS and assign Desktop/Mobile Class on body :

 function process(){ 
   if( $(window).width() > 600){
     $("body").removeClass("mobile").addClass("desktop");

   }else{
     $("body").removeClass("desktop").addClass("mobile");
   }

}
$(window).resize(function(){
    process()
});

现在,您已经执行了悬停命令,然后单击:

Now, you have execute the command for hover and click:

     $(document).on('mouseover', 'body.mobile .popover-controls div',function(e){
            alert("hover");
        }); 

 $(document).on('click', 'body.desktop .popover-controls div',function(e){
            alert("click");
     console.log("click");
        }); 

我希望这对您有用. :)

I Hope this will work for you. :)

检查Js小提琴示例: http://jsfiddle.net/asadalikanwal/xcj8p590/ 我刚刚为您创建,我也修改了我的代码

Check the Js fiddle Example: http://jsfiddle.net/asadalikanwal/xcj8p590/ I have just created for you, also i have modified my code

这篇关于根据宽度切换点击和悬停事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆