[英]Detect both mobile device and orientation to add a code
如果用戶在移動設備上並且方向是縱向的,我想向他們顯示文本。
為了檢測移動設備,我正在使用這個腳本:
if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)){
document.write("mobile");
}else{
document.write("not mobile");
}
對於縱向模式,我使用的是這個 CSS:
@media (orientation: portrait) {
.land-msg {display: block;}
}
但我不能將兩者結合起來相互合作。
你有辦法讓我在一個代碼中同時檢查移動設備和方向嗎?
媒體屏幕大小不起作用,因為我不希望它在桌面瀏覽器調整大小時顯示。
任何幫助表示贊賞。
我已使用以下代碼使其工作:
if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)){
if(window.innerHeight > window.innerWidth){
jQuery(".land-msg").css("display", "block");
}
}else{}
謝謝你。
您可以使用 matchMedia 來檢測方向(最小/最大寬度等)
const isMobile = (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) function matchMediaHandler(query) { if (query.matches) { // If media query matches (portrait) document.body.style.backgroundColor = "orange" document.body.innerText = isMobile? 'Mobile Portrait': 'Desktop Portrait' } else { document.body.style.backgroundColor = "yellowgreen" document.body.innerText = isMobile? 'Mobile Landscape': 'Desktop Landscape' } } // orientation query const orientation = matchMedia("(orientation: portrait)") // add listener orientation.addListener(matchMediaHandler) // trigger on load matchMediaHandler(orientation)
有純粹的 CSS 方法可以以比 userAvent 嗅探更好的方式檢測移動設備。 換句話說:永遠不要進行 userAgent 嗅探。 我 promise 你做錯了。
/* smartphones, touchscreens */
@media (hover: none) and (pointer: coarse) and (orientation: portrait) {
/* ... */
}
部分內容取自這里: https://ferie.medium.com/detect-a-touch-device-with-only-css-9f8e30fa1134
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.