简体   繁体   English

如何通过 screen.availWidth (而不是平板电脑,笔记本电脑等)准确检测手机

[英]How to accurately detect if mobile phone via screen.availWidth (and not tablet, laptop etc)

I'm working on a gallery.我在画廊工作。 I would like to show portrait oriented picutres to mobile phone users and landscape oriented pictures to everyone else (tablets, laptops etc).我想向手机用户展示纵向图片,向其他所有人(平板电脑、笔记本电脑等)展示横向图片。

What I currently have is:我目前拥有的是:

var maxW = window.screen.availWidth * window.devicePixelRatio;

if (maxW <= 767){
    galleryImages = portraitImages;
}else{
    galleryImages = landscapeImages;
};

var portraitImages = [  'https://static.photocdn.pt/images/articles/2016-7/landscape-comp/iStock_000058793850_Medium.jpg',
 'https://keyassets.timeincuk.net/inspirewp/live/wp-content/uploads/sites/12/2016/05/AP_Portrait_Landscapes_Stu_Meech-5.jpg',
 'https://keyassets.timeincuk.net/inspirewp/live/wp-content/uploads/sites/12/2016/05/AP_Portrait_Landscapes_Stu_Meech-16.jpg', 
'https://static.photocdn.pt/images/articles/2016-7/landscape-comp/iStock_000062009934_Medium.jpg']

var landscapeImages = ['https://images.unsplash.com/photo-1506744038136-46273834b3fb?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjM3Njd9&w=1000&q=80', 
'https://images.unsplash.com/photo-1506260408121-e353d10b87c7?ixlib=rb-1.2.1&w=1000&q=80', 
'https://www.tom-archer.com/wp-content/uploads/2017/03/landscape-photography-tom-archer-4.jpg', 
'https://s.yimg.com/uu/api/res/1.2/DdytqdFTgtQuxVrHLDdmjQ--~B/aD03MTY7dz0xMDgwO3NtPTE7YXBwaWQ9eXRhY2h5b24-/https://media-mbst-pub-ue1.s3.amazonaws.com/creatr-uploaded-images/2019-11/7b5b5330-112b-11ea-a77f-7c019be7ecae', 
'https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/hbx030117buzz14-1550595844.jpg']

Now, lets say, the smallest "resolution" for tablets is 768x1024.现在,可以说,平板电脑的最小“分辨率”是 768x1024。 When I go to Dev Tools, input 768x1024 in resolution and call alert("MaxW: " + maxW + ",\\nMaxH : " + maxH);当我去开发工具时,输入 768x1024 的分辨率并调用alert("MaxW: " + maxW + ",\\nMaxH : " + maxH); I get MaxW: 1536, MaxH: 2048 which is caused by the device-pixel ratio.我得到 MaxW: 1536, MaxH: 2048 这是由设备像素比引起的。

So, my question, how would I calculate the max screen size for a mobile phone, taking into consideration the device-pixel ratio.所以,我的问题是,考虑到设备像素比,我将如何计算手机的最大屏幕尺寸。

I can't very well say "show picture gallery if max-device width is 2048", since some computer monitors have worse resolution.我不能很好地说“如果最大设备宽度为 2048,则显示图片库”,因为某些计算机显示器的分辨率较差。

I hope I'm getting my meaning across.我希望我明白了我的意思。 If I can provide any additional information / explenation, let me know.如果我可以提供任何其他信息/解释,请告诉我。

Thank you for the help.感谢您的帮助。

With the innerWidth and innerHeight properties of the window you can calculate the width and height of your screen in pixels.使用窗口的innerWidthinnerHeight属性,您可以以像素为单位计算屏幕的宽度和高度。 On my 2560x1600 screen it returns the dimensions 1280x800 , accounting for the device-pixel ratio.在我的2560x1600屏幕上,它返回尺寸1280x800 ,占设备像素比。

function getWindowDimensions() {
  const width = window.innerWidth;
  const height = window.innerHeight;
  const ratio = (width / height) * 100;
  return { width, height, ratio };
}

const { width } = getWindowDimensions();

if (width < 768) {
    galleryImages = portraitImages;
} else {
    galleryImages = landscapeImages;
}

Also, instead of selecting your images in JavaScript you could also use the <picture> element and use the srcset attribute.此外,您还可以使用<picture>元素并使用srcset属性,而不是在 JavaScript 中选择图像。 With the <picture> element you can add media queries for showing images based on the condition in that query.使用<picture>元素,您可以添加媒体查询以根据该查询中的条件显示图像。 This would give you the ability to add both your image sets to the HTML and the browser then decides which image to show based on your query.这将使您能够将图像集添加到 HTML,然后浏览器会根据您的查询决定显示哪个图像。

<picture>
  <source media="(max-width: 767px)" srcset="portrait.jpg">
  <source media="(min-width: 768px)" srcset="landscape.jpg">
  <img src="landscape.jpg" alt="Your image description">
</picture>

I'd suggest that you create pairs for your images to add the to the picture element.我建议您为您的图像创建对以添加到图片元素。 For example in an array of objects with the keys portrait and landscape .例如,在具有键portraitlandscape的对象数组中。 Loop over the array and create a <picture> element for each of those pairs with the <source> tags specified to the media query and its corresponding srcset value.循环遍历数组并为每个对创建一个<picture>元素,其中包含为媒体查询指定的<source>标签及其对应的srcset值。

const images = [
  {
    portrait: './portrait-image-1.jpg',
    landscape: './landscape-image-1.jpg'
  },
  {
    portrait: './portrait-image-2.jpg',
    landscape: './landscape-image-2.jpg'
  },
  {
    portrait: './portrait-image-3.jpg',
    landscape: './landscape-image-3.jpg'
  }
];

for (const { portrait, landscape } of images) {

  const picture = document.createElement('picture');
  const sourcePortrait = document.createElement('source');
  const sourceLandscape = document.createElement('source');
  const image = document.createElement('img');

  sourcePortrait.media = '(max-width: 767px)';
  sourcePortrait.srcset = portrait;
  sourceLandscape.media = '(min-width: 768px)';
  sourceLandscape.srcset = landscape;
  image.src = landscape;

  picture.append(sourcePortrait, sourceLandscape, image);
  document.body.append(picture);

}

Otherwise to detect the device that someone is using, like a mobile phone, then check the userAgent for keywords that are recognized as phones.否则,要检测某人正在使用的设备(例如手机), 请检查userAgent以查找识别为手机的关键字 For detecting devices this is good, but for responsive web development, not so much as many other devices and new browser could be added and could break in the future.对于检测设备来说,这很好,但是对于响应式 Web 开发,没有那么多其他设备和新浏览器可以添加并且将来可能会崩溃。

Why are you assuming that portrait=phone and landscape=tablet?你为什么假设纵向=手机和横向=平板电脑? I could (and probably would for a gallery) be using my phone in landscape.我可以(并且可能会为画廊)在横向使用我的手机。

Rather than making assumptions about the type of device, check for what the screen is actually doing now, ie is the screen landscape or portrait, and then configure your software accordingly.不要假设设备的类型,而是检查屏幕现在实际在做什么,即屏幕是横向还是纵向,然后相应地配置您的软件。

Then it will work no matter what device and no matter what orientation.然后无论什么设备,无论什么方向,它都可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如果(screen.availWidth&gt;)禁用所有脚本? - if ( screen.availWidth > ) disables all scripts? javascript 中 screen.width 和 screen.availwidth 的区别 - screen.width and screen.availwidth difference in javascript JavaScript 在 setInterval 调用的函数中使用 screen.width 或 screen.availWidth 时未获取更新值 - JavaScript Not getting an updated value when using screen.width or screen.availWidth in a function which is called by setInterval Impact如何知道设备是台式机,手机,平板电脑等(任何设备)? - How does Impact know whether a device is a desktop, a mobile phone, a tablet, etc (Any Device)? 检测手机与平板电脑 - Detect phone vs tablet 更好地通过屏幕大小来处理台式机还是手机还是平板电脑,还是检测平板电脑/手机/台式机? - Better to handle desktop vs phone vs tablet by screen size or detect tablet/phone/desktop? 仅自动检测移动浏览器(通过用户代理?)而不检测平板电脑 - Auto detect only mobile browser (via user-agent?) not tablet 使用脚本而非平板电脑检测电话 - detect phone with script and not tablet 平板电脑和带触摸屏的笔记本电脑有什么区别? - What the difference between tablet and laptop with touch screen? 在Javascript中(或通过CSS)检测小(移动)屏幕 - Detect small (mobile) screen in Javascript (or via css)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM