![](/img/trans.png)
[英]Click on button to display div which should be fixed when scrolling down. Div not showing properly though?
[英]fixed div showing when scrolling down on mobile
我網站上的固定菜單有問題。 這個想法是它在向下滾動 200 像素(#menu)后仍保持在頂部。 所以我創建了一個額外的菜單,只在 200px (#menu-scroll) 后顯示,向上滾動時消失。 所有這些都使用我找到的 js 解決方案,並且效果很好。 現在的問題是該網站的移動版本。 現在,在我的手機上向下滾動 200 像素后,始終顯示的 div:none 出現了。 我需要的是激活#menu-scroll 的代碼在移動設備上不再起作用,因此 div 與 display:none 保持不可見。 我想答案是在 js 中,但我不知道 js。 所以請,任何幫助將不勝感激。
jsfiddle: jsfiddle.net/695q9tdx/
我的網站(嘗試在手機上觀看): http : //armandorodriguez.pe/uh/
謝謝。
那么你可以做的是在頁面加載時設置它,如果它是移動/平板設備,甚至不創建滾動事件偵聽器。
實現這一點的最簡單方法是使用沿 JS Navigator
對象發送的user-agent
字符串。
// This function checks if the userAgent property matches any
// of the typical mobile/tablet devices, separated by the pipeline '|'
// character.
// If no matches are found, the .match function returns null
// So if (null == null) or (null != null) then we can have a
// simple boolean return value
function isDesktop() {
var regexStr = /Android|webOS|iPhone|iPod|iPad|Blackberry/i;
return (navigator.userAgent.match(regexStr) == null)
}
現在,如果您在頁面加載中包含該功能作為門scroll
事件邏輯的一種方式,您幾乎可以在桌面/移動設備上禁用該操作:
// Now that we have a way to check if the client is on a Desktop
// on page load, we can setup a scroll event listener only if
// he/she isn't on a tablet/mobile device.
if (isDesktop()) {
// **ANYTHING** wrapped within the function(){} statement
// parameter you pass into the $(x).scroll() function **WILL**
// get executed on each event fire, so you can include multiple
// logic checks or functions within it.
// Keep in mind though, the more weight added into an event fire
// can cause lag on the client side, which is why I recommend
// adding an event decoupler in the future
$(window).scroll(function(){
if ($(window).scrollTop() > 200) {
$("#menu-scroll").fadeIn("fast");
}
else if ($(window).scrollTop() < 200) {
$("#menu-scroll").fadeOut("fast");
}
});
}
我建議在#menu-scroll
添加/刪除一些特殊的類名, fadeIn
在用戶滾動時不斷調用fadeIn
或fadeOut
。 這樣,當您在收聽滾動事件時,您實際上可以添加邏輯以僅在它們具有相反的類名時才淡入或淡出。
另外,還有一個注意事項。 這只會像我在頁面加載中所說的那樣工作。 頁面加載后,如果您將瀏覽器調整為較小的寬度或測試不同的設備(即使用 Chrome 開發人員工具) ,則不會啟用偵聽器。
一個簡單的解決方法是確定寬度斷點並將其包含在 js 周圍的 if 語句中。
/* set breakpoint for mobile device */
var breakpoint = 777px;
/* only execute menu code if larger than breakpoint */
if($(window).width() > breakpoint){
$(window).scroll(function(){
if($(window).scrollTop() > 200){
$("#menu-scroll").fadeIn("fast");
}
});
$(window).scroll(function(){
if($(window).scrollTop() < 200){
$("#menu-scroll").fadeOut("fast");
}
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.