如何在特定设备宽度下禁用JQuery?

时间:2016-12-01 10:21:53

标签: javascript jquery html css responsive-design

我希望在移动设备宽度(768px及以下)停止JQuery功能。 我已经尝试使用$(window).width()来检测屏幕宽度,然后使用if语句,但似乎无法使其正常工作。

$(document).ready(function(){
  var resolution = $(window).width();
  if (resolution >= 768) {
    $('.img-1').hover(function(){
        $(this).animate({right: "350px"},1000);
        $('#desc1').show(1000);
    });
    $('.img-1').mouseleave(function(){
        $(this).animate({right: "0px"},1000);
        $('#desc1').hide(1000);
    });
  } else {
    // NO SCRIPT
  }
});

以下是指向其代码的链接:http://codepen.io/SRBET/pen/dOJoJb/

非常感谢任何帮助!

由于

3 个答案:

答案 0 :(得分:1)

试试这个:

var resolution = $(window).width();
if (resolution > 768) {

  $(document).ready(function(){

  $('.img-1').hover(function(){
     $(this).animate({right: "350px"},1000);
     $('#desc1').show(1000);
 });
 $('.img-1').mouseleave(function(){
    $(this).animate({right: "0px"},1000);
    $('#desc1').hide(1000);
 });
});

} else {
// NO SCRIPT
}

在就绪功能之前使用if条件。它在代码面板中工作(我在chrome上尝试过)。如果您希望它不适用于768px,也请删除等号。

答案 1 :(得分:1)

Jquery $(selector).off()用于删除Jquery事件。 在更新的codepen中找到解决方案: http://codepen.io/Debabrata89/pen/xRpwOG。 刷新768px以下的页面,看看没有调用$('。img-1')。hover()函数。还有$(document).ready(),使用$(window).resize()和debouncing函数并在其中写下逻辑。

 var resolution = $(window).width();
if (resolution >= 768) {

$(document).ready(function(){
$('.img-1').hover(function(){
    $(this).animate({right: "350px"},1000);
    $('#desc1').show(1000);
});
$('.img-1').mouseleave(function(){
    $(this).animate({right: "0px"},1000);
    $('#desc1').hide(1000);
});
});
  } else {
$('.img-1').off("hover");
}

$(document).ready(function(){
$('.img-2').hover(function(){
    $(this).animate({right: "350px"},1000);
    $('#desc2').show(1000);
});
$('.img-2').mouseleave(function(){
    $(this).animate({right: "0px"},1000);
    $('#desc2').hide(1000);
});
});

答案 2 :(得分:1)

我们希望实现两件事。

  • 确保效果可以在移动设备上应用net。
  • 当屏幕宽度变为超过768像素时,请确保应用效果执行

那么,我们怎样才能以最合乎逻辑的方式实现这一目标呢?

var resetEvents = function() {
	$('.img-1').off()
	$('#desc1').off()
	checkScreen();
}

var checkScreen = function() {
  if ($(window).width() >= 768) {
    $('.img-1').hover(function(){
        $(this).animate({right: "350px"},1000);
        $('#desc1').show(1000);
    });
    $('.img-1').mouseleave(function(){
        $(this).animate({right: "0px"},1000);
        $('#desc1').hide(1000);
    });
  }
}

$(document).ready(function(){
	resetEvents();
	$(window).resize(function() {
		resetEvents()
	});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="img-1">hi, i'm img-1</div>
<div style="display:none;" id="desc1">hi, i'm desc1</div>

(全屏打开以查看正在运行的事件,以及小屏幕以查看它们已禁用)

我已将代码包装在多个函数中,并在$(document).ready()上调用第一个函数。第一个函数重置元素上的所有当前事件侦听器。然后调用第二个函数。

在第二个函数中,我们检查窗口的(new?)宽度,并在满足要求时应用事件监听器。最后,我们确保将resetEvents()事件附加到resize事件,因此当有人在iPad上更改方向时,他或她仍然可以体验事件。

相关问题