我想你正在寻找的是
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/themes/redmond/jquery-ui.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.js"></script>
</head>
<body>
<div class="clickme">Click Me</div>
</body>
<script>
$(document).ready(function(){
var handler = function(){
console.log("clicked");
};
var $window = $(window);
var setClickHandler = function(){
if($window.width() > 900){
var registered = false;
var events = $(".clickme").data("events");
if(events){
var handlers = $(".clickme").data("events").click;
if(handlers){
$.each(handlers, function(index, e){
if(e.handler == handler){
registered = true;
}
});
}
}
if(!registered){
$(".clickme").on("click", handler );
}
} else {
$(".clickme").off("click", handler );
}
};
setClickHandler();
$window.on("resize", setClickHandler);
});
</script>
</html>
它看起来有点复杂,但这是我能想到的最好的。
这里我们根据窗口宽度注册和注销处理程序。
另一个简单的解决方案是检查处理程序中的条件
$(document).ready(function(){
var handler = function(){
if($window.width() > 900){
console.log("clicked");
}
};
var $window = $(window);
$(".clickme").on("click", handler );
});