我想做一些看似简单的事情:点击或触摸div时将div变为绿色。 (实际上,这是一个可以按任意秒数的按钮)。
我几乎让它在这个小提琴中工作: https://jsfiddle.net/lrodgi/66gramjh/
我在做什么(几乎有效),只是为了监听鼠标和触发事件以便发布:
jbtn.on('mousedown touchstart', function(event) {
onPressed();
});
$(document).on('mouseup touchend', function() {
onReleased();
});
这在计算机上运行良好,但在移动浏览器中,保持一段时间后出现的上下文菜单会破坏它。因此,我阻止该菜单出现:
function onContextMenu(event) {
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
return false;
}
jbtn.on('contextmenu', onContextMenu);
有了这些,它似乎在所有桌面浏览器和移动Chrome中都能正常运行。但是,它仍无法在Firefox Mobile中正常运行。
在Firefox手机中,当我按住div几秒钟时,没有菜单出现,而是一个触摸屏'事件被提出。不是touchend或mouseup。所以div永远不会被释放。
任何想法让它完美运作?
我不介意使用javascript库。事实上,我已经尝试过jQuery Mobile的vmouseup和vmousedown事件,没有成功(几秒钟后发生的touchcancel也阻止了vmouseup的提升)。
答案 0 :(得分:0)
CSS pseudo selectors :active
和:focus
怎么样?
#btn {
background-color: green;
}
#btn:active, #btn:focus {
background-color: red;
}
.all {
// Just in case.
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
-webkit-touch-callout: none;
user-select: none;
touch-callout: none;
}
#btn {
background-color: green;
}
#btn:active, #btn:focus {
background-color: red;
}
<div class="all">
<div id="btn" class="released" style="width: 50px; height: 50px">
</div>
</div>
答案 1 :(得分:0)
问题的根源在于,在Firefox mobile中,当拦截'contextmenu'事件时,会出现'touchcancel'事件。
我目前在Firefox手机中找不到防止JavaScript的'contextmenu',同时能够检测到实际触摸结束的时间('touchcancel'被提升然后没有'touchend'发生,即使用户仍然保持触摸)。
然而,我发现的解决方法是通过CSS确保我不需要使用<img>
标记(这将导致长按下的保存图像上下文菜单),使用用户不需要“上下文菜单”预防-select:none以避免复制粘贴上下文菜单等。
看似有效的片段:
function onPressed() {
$("#btn").addClass("pressed");
$("#btn").removeClass("released");
}
function onReleased() {
$("#btn").addClass("released");
$("#btn").removeClass("pressed");
}
var jbtn = $("#btn");
jbtn.on('mousedown touchstart', function(event) {
onPressed();
});
$(document).on('mouseup touchend', function() {
onReleased();
});
jbtn.on('mouseup mouseleave touchend', function() {
onReleased();
});
.all {
// Just in case.
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
-webkit-touch-callout: none;
user-select: none;
touch-callout: none;
}
.pressed {
background-color: red;
}
.released {
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="all">
<div id="btn" class="released" style="width: 50px; height: 50px">
</div>
</div>
<textarea>
Just testing
</textarea>
值得注意的是,如果我需要切换<img>
而不是在div上切换背景颜色,则此解决方案将无法正常工作。 (弹出保存图像对话框,并且无法使用contextmenu事件来阻止它。)