2017-08-10 52 views
0

我在jQuery中使用fadeIn和fadeOut,它在桌面上工作正常。但是,在移動設備上(我只在iPhone上測試過),觸摸外部元素後,子div會觸摸但不會隱藏。我對jQuery相當陌生,所以我不確定我可以在這裏實現什麼樣的解決方案。也許移動檢測和執行觸摸來打開/隱藏,但我不知道如何做到這一點。這裏是我的jsfiddle:jQuery:淡入淡出/淡入淡出 - 移動設備上的替代品?

https://jsfiddle.net/9LL3mmzt/

的jQuery:

$(document).ready(function() { 
    $(".parent").hover(function() { 
    $(this).children(".child").fadeIn("fast"); 
    }, function() { 
    $(this).children(".child").fadeOut("fast"); 
    }); 
}); 

HTML:

<div class="parent"> 
    <span>Peek-A-</span> 
    <div class="child"> 
    <span>Boo</span> 
    </div> 
</div> 

CSS:

.child { 
    display: none; 
} 

我試圖從該線程中的第一個解決方案: time-out on jQuery hover function

但是,由於我的知識有限,無法正常工作。

回答

1

懸停功能並非真的應該在觸控設備上使用。我認爲你需要檢查touchstart功能。

編輯1: 一個例子是這樣的:

$('div.example').on("touchstart", function (e) { 
    alert('testing'); 
}); 

但是要記住,你仍然可以使用你的懸停JavaScript,但你必須只使用它沒有觸摸設備指定。請參閱Modernizr

希望這會有所幫助。

僅供參考@James Douglas您可以看到我無法發表任何評論,因爲我的聲譽得分。如果可能請評論或幫助我們找到這個問題的答案,我認爲這會更有用。

編輯2:Modernizr非常方便。在你的情況下,你會得到一個類的觸摸或不觸摸(在html元素),取決於你是哪個設備。

所以在我的例子中,你可以使用它那麼作爲$(「觸摸div.example」)......

有可能不同的解決方案,但我認爲這是最好的辦法(另見What's the best way to detect a 'touch screen' device using JavaScript?)。您只需將de modernizr.js文件添加到您的網站(最好在您的網頁的頭部)。

編輯3:我測試了你的jsfiddle在iPhone和Android上的例子,它的工作原理。所以對我來說這是一件好事。

+0

如果你願意詳細一點日請編輯你的答案。如果沒有,您應該將其作爲評論發佈。 –

+0

@Nick一個例子會很好! –

+0

@Nick,是否可以使用if/else語句而不是使用Modernizr?看起來它太複雜了。 –

0

我是能夠使這項工作(至少在iPhone上),使用從@尼克的帖子的例子,從線程我在OP連接解決方​​案:

這裏的的jsfiddle:https://jsfiddle.net/tkeaoffd/

JQuery的:

$(document).ready(function() { 
    function hasTouch() { 
    try { 
     document.createEvent("TouchEvent"); 
     return (true); 
    } catch (e) { 
     return (false); 
    } 
    } 
    var touchPresent = hasTouch(); 
    $('.parent').hover(function() { 
    var caption = $(this).find('.child'); 
    caption.stop(true, true).fadeIn("fast"); 
    if (touchPresent) { 
     $('.parent').on("touchstart", function(e) { 
     $(this).children(".child").fadeToggle("fast"); 
     }); 
    } 
    }, function() { 
    $(this).find('.child').stop(true, true).fadeOut("fast"); 
    }); 
}); 

HTML/CSS:

<div class="parent"> 
    <span>Peek-A-</span> 
    <div class="child"> 
    <span>Boo</span> 
    </div> 
</div> 


.child { 
    display: none; 
}