[英]How to trigger long-press (click-and-hold) on mobile devices with Vue / JavaScript
這僅適用於移動設備。 它在桌面上按預期工作,因此我將省略所有這些 styles 和功能。
我有一個這樣的 Vue-component:
模板
<div class="container">
<div class="invisible-overlay-styles">
<button
v-if="! videoIsPlaying"
@click="playVideo()"
@mousedown="playVideo()"
>
</button>
<a
v-if="videoIsPlaying"
>
</a>
</div> <!-- invisible-overlay-styles -->
<video ... />
</div>
所有的 div、按鈕、錨點和視頻都堆疊在一起,使用display: block
和position: absolute; width: 100%; etc. etc. etc.
position: absolute; width: 100%; etc. etc. etc.
方法
playVideo(){
console.log( 'Im playing!!' );
if( this.player ){
if( this.player.paused ){
this.player.play()
}
}
}
如果我點擊它,它會正常工作:
但是如果我點擊並按住,那么@click
和@mousedown
都不會被觸發。 這兩者都在:
所以兩個問題:
@click
沒有被觸發,因為它是@mousedown
和@mouseup
的組合。 但是為什么當我長@mousedown
沒有被觸發?您需要使用TouchEvent API或PointerEvent API 。
兩者的瀏覽器兼容性都很好:
它們每個都有與 MouseEvent API 相似的事件,即touchstart
= mousedown
。
我個人發現 TouchEvents 比 PointerEvents 更好,但是,您可能需要進行一些測試,看看哪種最適合您的情況。
因此,正如您可以使用 Vue 猜測的那樣,您可以使用@touchstart
:
<button
v-if="!videoIsPlaying"
@click="playVideo()"
@mousedown="playVideo()"
@touchstart="playVideo()"
/>
如果你想將其確定為長按,你必須存儲在一個值touchstart
,改變它touchend
:
<button
@touchstart="touching = true"
@touchend="touching = false"
/>
...
data() {
return {
touching: false
}
}
嘗試使用@contextmenu.prevent="func"
。 當我按住電話中的某個元素時,這對我有用。 但是,就像右鍵單擊一樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.