![](/img/trans.png)
[英]What is the best way to detect websocket support using Javascript?
[英]What is the best way to detect retina support on a device using JavaScript?
現在我正在使用這個功能:
function is_retina_device() {
return window.devicePixelRatio > 1;
}
但它的簡單讓我害怕。 有沒有更徹底的檢查?
根據我最近閱讀的所有內容,瀏覽器似乎正在朝着resolution
媒體查詢表達式的方向發展。 這不是當前接受的答案中使用的device-pixel-ratio
。 device-pixel-ratio
應該只用作后備的原因是因為它不是標准的媒體查詢。
根據 w3.org:
曾幾何時,Webkit 決定需要對屏幕分辨率進行媒體查詢。 但是他們沒有使用已經標准化的分辨率媒體查詢,而是發明了 -webkit-device-pixel-ratio。
由於resolution
是標准化的,因此未來讓我們首先在檢測中使用它以備將來證明。 另外因為我不確定您是只想檢測高 dppx 設備還是只檢測視網膜(僅限 Apple)設備,所以我分別添加了一個。 最后,請注意,Apple 檢測只是用戶代理嗅探,因此不能依賴。 注意:對於isRetina
函數,我使用 dppx 為 2 而不是 1.3,因為所有視網膜蘋果設備都有 2dppx。
請注意,似乎MS Edge 在非整數值方面存在一些問題
function isHighDensity(){
return ((window.matchMedia && (window.matchMedia('only screen and (min-resolution: 124dpi), only screen and (min-resolution: 1.3dppx), only screen and (min-resolution: 48.8dpcm)').matches || window.matchMedia('only screen and (-webkit-min-device-pixel-ratio: 1.3), only screen and (-o-min-device-pixel-ratio: 2.6/2), only screen and (min--moz-device-pixel-ratio: 1.3), only screen and (min-device-pixel-ratio: 1.3)').matches)) || (window.devicePixelRatio && window.devicePixelRatio > 1.3));
}
function isRetina(){
return ((window.matchMedia && (window.matchMedia('only screen and (min-resolution: 192dpi), only screen and (min-resolution: 2dppx), only screen and (min-resolution: 75.6dpcm)').matches || window.matchMedia('only screen and (-webkit-min-device-pixel-ratio: 2), only screen and (-o-min-device-pixel-ratio: 2/1), only screen and (min--moz-device-pixel-ratio: 2), only screen and (min-device-pixel-ratio: 2)').matches)) || (window.devicePixelRatio && window.devicePixelRatio >= 2)) && /(iPad|iPhone|iPod)/g.test(navigator.userAgent);
}
如果您想要它用於圖像,您可以使用retinajs或者此代碼是檢測它的常見響應:
function isRetinaDisplay() {
if (window.matchMedia) {
var mq = window.matchMedia("only screen and (min--moz-device-pixel-ratio: 1.3), only screen and (-o-min-device-pixel-ratio: 2.6/2), only screen and (-webkit-min-device-pixel-ratio: 1.3), only screen and (min-device-pixel-ratio: 1.3), only screen and (min-resolution: 1.3dppx)");
return (mq && mq.matches || (window.devicePixelRatio > 1));
}
}
實際上,如果您只關心現代瀏覽器,那么您在問題中使用的代碼是完全正確的。 (參見: http : //caniuse.com/#feat=devicepixelratio )
所有現代瀏覽器都實現了它,舊瀏覽器只會為您提供較低分辨率的圖像。 我不希望 IE10- 出現在視網膜/高分辨率設備上。 另外,在 JavaScript 中使用 CSS 檢查是否比使用本機窗口屬性更奇怪?
哎呀,devicePixelRatio 瀏覽器支持甚至比分辨率規范還要好。 (見: http : //caniuse.com/#feat=css-media-resolution )
我想說它實際上使用起來非常安全,我們在每月訪問量超過 1000 萬的生產網站中使用它。 按預期工作。
我唯一要改變的是函數名稱,因為加載高分辨率圖像的需要在技術上並不意味着屏幕是視網膜。 實際上,您甚至不需要數字檢查,因為undefined > 1
導致false
。
function is_high_resolution_screen() {
return window.devicePixelRatio > 1;
}
devicePixelRatio 根本不可靠。 當您放大到 200% 時,window.devicePixelRatio 將返回 2,但您不在視網膜顯示器上。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.