我们在开发移动端web项目时经常遇到设置border:1px,但是显示的边框却为2px或是3px粗细,这是因为设备像素比devicePixelRatio为2或3引起的。

何为“设备像素比devicePixelRatio”

设备上物理像素和设备独立像素(device-independent pixels (dips))的比例。
公式表示就是:window.devicePixelRatio = 物理像素 / dips   dip或dp,(device independent pixels,设备独立像素)与屏幕密度有关。dip可以用来辅助区分视网膜设备还是非视网膜设备。

所有非视网膜屏幕的iphone在垂直的时候,宽度为320物理像素。当你使用<meta name="viewport" content="width=device-width">的时候,会设置视窗布局宽度(不同于视觉区域宽度,不放大显示情况下,两者大小一致,见下图)为320px, 于是,页面很自然地覆盖在屏幕上。这样,非视网膜屏幕的iphone上,屏幕物理像素320像素,独立像素也是320像素,因此,window.devicePixelRatio等于1.

而对于视网膜屏幕的iphone,如iphone4s, 纵向显示的时候,屏幕物理像素640像素。同样,当用户设置<meta name="viewport" content="width=device-width">的时候,其视区宽度并不是640像素,而是320像素,这是为了有更好的阅读体验 – 更合适的文字大小。
这样,在视网膜屏幕的iphone上,屏幕物理像素640像素,独立像素还是320像素,因此,window.devicePixelRatio等于2.

每个像素点实际上有4倍的普通像素点,如下示意(© smashingmagazine):

1个CSS像素点实际上有4个位图像素点,1个分成4个,显然不够分啊,只能颜色近似选取,于是,图片感觉就是模糊的(© smashingmagazine)!。这就是为什么使用两倍图。

视网膜屏幕下图片就显示OK了(非视网膜屏幕图片被压缩-减少像素取样——资源浪费!)

在retina屏下面,如果你写了这样的meta <meta name="viewport" content="initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no"> 
你将永远无法写出1px宽度的东西,除此之外,inline的SVG等元素,也会按照逻辑像素来渲染,整个页面的清晰度会打折;

百度糯米的实现:

 @media only screen and (-webkit-min-device-pixel-ratio:),only screen and (min-device-pixel-ratio:) {
.normal-goods .good-content {
border: none;
background-image: -webkit-linear-gradient(90deg,#e0e0e0,#e0e0e0 %,transparent %);
background-image: -moz-linear-gradient(90deg,#e0e0e0,#e0e0e0 %,transparent %);
background-image: -o-linear-gradient(90deg,#e0e0e0,#e0e0e0 %,transparent %);
background-image: linear-gradient(,#e0e0e0,#e0e0e0 %,transparent %);
background-size: % 1px;
background-repeat: no-repeat;
background-position: bottom
}
}

大众点评的实现:

 .index-rec .home-tuan-list .cnt {
padding: 7px 10px 10px ;
display: box;
display: -webkit-box;
display: -ms-flexbox;
height: 78px;
background-image: url(//www.dpfile.com/mod/app-m-style/1.7.2/css/img/repeat-x.png);
background-repeat: repeat-x;
background-position: bottom;
background-size: auto 1px
}

微信WeUI的实现:

 .weui_grid:before {
content: " ";
position: absolute;
right: ;
top: ;
width: 1px;
height: %;
border-right: 1px solid #D9D9D9;
color: #D9D9D9;
-webkit-transform-origin: %;
transform-origin: %;
-webkit-transform: scaleX(0.5);
transform: scaleX(0.5);
right: -1px;
}
 .weui_grid:after {
content: " ";
position: absolute;
left: ;
bottom: ;
width: %;
height: 1px;
border-bottom: 1px solid #D9D9D9;
color: #D9D9D9;
-webkit-transform-origin: %;
transform-origin: %;
-webkit-transform: scaleY(0.5);
transform: scaleY(0.5);
}
 

阿里的实现:

js:

 <script>
if (/iP(hone|od|ad)/.test(navigator.userAgent)) { // 就是放到html根节点上的 ios8现在普及率高了,可以省略
var v = (navigator.appVersion).match(/OS (\d+)_(\d+)_?(\d+)?/), version = parseInt(
v[], );
if (version >= ) {
document.documentElement.classList.add('hairlines')
}
};
</script>

css:

 .r1bt {
border-top: 1px solid rgba(,,,.)
}
.r1bb {
border-bottom: 1px solid rgba(,,,.)
}
.r1bl {
border-left: 1px solid rgba(,,,.)
}
.r1br {
border-right: 1px solid rgba(,,,.)
}
.r1b {
border: 1px solid rgba(,,,.)
}
.hairlines .r1bt,.hairlines .r1bb,.hairlines .r1bl,.hairlines .r1br,.hairlines .r1b {
border-width: .5px!important
}

阿里的另一种实现:

 /*Retian 1px border start */
.retinabt,.retinabb,.retinabl,.retinabr,.retinab{position:relative;}
.retinabt:before,.retinabb:after{pointer-events:none;position:absolute;content:"";height:1px;background:rgba(,,,.);left:;right:;z-index:;}
.retinabt:before{top:;z-index:;}
.retinabb:after{bottom:;z-index:;}
.retinabl:before,.retinabr:after{pointer-events:none;position:absolute;content:"";width:1px;background:rgba(,,,.);top:;bottom:}
.retinabl:before{left:;z-index:;}
.retinabr:after{right:;z-index:;}
.retinab:after{position:absolute;content:"";top:;left:;-webkit-box-sizing:border-box;box-sizing:border-box;width:%;height:%;border:1px solid rgba(,,,.);pointer-events:none;z-index:;}
@media (-webkit-min-device-pixel-ratio:1.5),(min-device-pixel-ratio:1.5),(min-resolution:144dpi),(min-resolution:.5dppx){
.retinabt:before,.retinabb:after{-webkit-transform:scaleY(.);transform:scaleY(.) }
.retinabl:before,.retinabr:after{-webkit-transform:scaleX(.);transform:scaleX(.) }
.retinab:after{width:%;height:%;-webkit-transform:scale(.);transform:scale(.) }
.retinabt:before,.retinabl:before,.retinab:after{-webkit-transform-origin: ;transform-origin: }
.retinabb:after,.retinabr:after{-webkit-transform-origin:% %;transform-origin:% %}
}
@media (-webkit-device-pixel-ratio:1.5){
.retinabt:before,.retinabb:after{-webkit-transform:scaleY(.);transform:scaleY(.) }
.retinabl:before,.retinabr:after{-webkit-transform:scaleX(.);transform:scaleX(.)}
.retinab:after{width:%;height:%;-webkit-transform:scale(.);transform:scale(.) }
}
@media (-webkit-device-pixel-ratio:){
.retinabt:before,.retinabb:after{-webkit-transform:scaleY(.);transform:scaleY(.)}
.retinabl:before,.retinabr:after{-webkit-transform:scaleX(.);transform:scaleX(.)}
.retinab:after{width:%;height:%;-webkit-transform:scale(.);transform:scale(.)}
}
@media (-webkit-min-device-pixel-ratio:),(min-device-pixel-ratio:){
.retinabt:before,.retinabb:after{-webkit-transform:scaleY(.);transform:scaleY(.)}
.retinabl:before,.retinabr:after{-webkit-transform:scaleX(.);transform:scaleX(.)}
.retinab:after{width:%;height:%;-webkit-transform:scale(.);transform:scale(.)}
}
/*Retina 1px border end */

美团的实现:

 <script type="text/javascript">
//根据屏幕大小及dpi调整缩放和大小
(function() {
var scale = 1.0;
var ratio = ;
if (window.devicePixelRatio >= ) {
scale *= 0.5;
ratio *= ;
}
var text = '<meta name="viewport" content="initial-scale=' + scale + ', maximum-scale=' + scale +', minimum-scale=' + scale + ', width=device-width, user-scalable=no" />';
document.write(text);
document.documentElement.style.fontSize = *ratio + "px";
})();
</script>

我们把美团的 拷贝过来使用,发现 安卓自带的浏览器(app内嵌h5不得不考虑)有的 不兼容 开始整体字体放大,应该是没有正确获取设备的实际宽度,(手头没有那么多安卓测试手机,主要是自带浏览器出现问题),不知到美团怎么处理的,我想到的用这个   target-densittydpi=device-dpi   hack下;是可以的 或者加个 计时器 延迟 50毫秒 获取设备的正确实际宽度;

 <meta name="viewport" content="target-densitydpi=device-dpi">  <!--安卓自带的 device-width 先不加 否则iphone 随进线条出现问题 -->
<script>
+function(win,doc,undefined) {//根据屏幕大小及dpi调整缩放和大小
var scale = 1.0,ratio = ,dc=doc,viewporttexts='';
if (win.devicePixelRatio && devicePixelRatio >= 1.5) {
ratio = devicePixelRatio;
scale = scale/(devicePixelRatio);
}
//var texts = '<meta name="viewport" content="initial-scale=' + scale + ', maximum-scale=' + scale +', minimum-scale=' + scale + ', width=device-width, user-scalable=no" />';
// dc.write(texts);
viewporttexts = ' width=device-width, initial-scale=' + scale + ', maximum-scale=' + scale +', minimum-scale=' + scale + ',user-scalable=no';
doc.querySelector('meta[name="viewport"]').setAttribute("content",viewporttexts); console.log('');
dc.documentElement.style.fontSize =doc.getElementsByTagName("html")[].style.fontSize=Math.ceil(*ratio) + "px";
}(window,document);
</script>

设计坞官网https://www.wode007.com/sites/73738.html

淘宝的实现:

 ;(function(win, lib) {
var doc = win.document;
var docEl = doc.documentElement;
var metaEl = doc.querySelector('meta[name="viewport"]');
var flexibleEl = doc.querySelector('meta[name="flexible"]');
var dpr = ;
var scale = ;
var tid;
var flexible = lib.flexible || (lib.flexible = {}); if (metaEl) {
console.warn('将根据已有的meta标签来设置缩放比例');
var match = metaEl.getAttribute('content').match(/initial\-scale=([\d\.]+)/);
if (match) {
scale = parseFloat(match[]);
dpr = parseInt( / scale);
}
} else if (flexibleEl) {
var content = flexibleEl.getAttribute('content');
if (content) {
var initialDpr = content.match(/initial\-dpr=([\d\.]+)/);
var maximumDpr = content.match(/maximum\-dpr=([\d\.]+)/);
if (initialDpr) {
dpr = parseFloat(initialDpr[]);
scale = parseFloat(( / dpr).toFixed());
}
if (maximumDpr) {
dpr = parseFloat(maximumDpr[]);
scale = parseFloat(( / dpr).toFixed());
}
}
} if (!dpr && !scale) {
var isAndroid = win.navigator.appVersion.match(/android/gi);
var isIPhone = win.navigator.appVersion.match(/iphone/gi);
var devicePixelRatio = win.devicePixelRatio;
if (isIPhone) {
// iOS下,对于2和3的屏,用2倍的方案,其余的用1倍方案
if (devicePixelRatio >= && (!dpr || dpr >= )) {
dpr = ;
} else if (devicePixelRatio >= && (!dpr || dpr >= )){
dpr = ;
} else {
dpr = ;
}
} else {
// 其他设备下,仍旧使用1倍的方案
dpr = ;
}
scale = / dpr;
} docEl.setAttribute('data-dpr', dpr);
if (!metaEl) {
metaEl = doc.createElement('meta');
metaEl.setAttribute('name', 'viewport');
metaEl.setAttribute('content', 'initial-scale=' + scale + ', maximum-scale=' + scale + ', minimum-scale=' + scale + ', user-scalable=no');
if (docEl.firstElementChild) {
docEl.firstElementChild.appendChild(metaEl);
} else {
var wrap = doc.createElement('div');
wrap.appendChild(metaEl);
doc.write(wrap.innerHTML);
}
} function refreshRem(){
var width = docEl.getBoundingClientRect().width;
if (width / dpr > ) {
width = * dpr;
}
var rem = width / ;
docEl.style.fontSize = rem + 'px';
flexible.rem = win.rem = rem;
} win.addEventListener('resize', function() {
clearTimeout(tid);
tid = setTimeout(refreshRem, );
}, false);
win.addEventListener('pageshow', function(e) {
if (e.persisted) {
clearTimeout(tid);
tid = setTimeout(refreshRem, );
}
}, false); if (doc.readyState === 'complete') {
doc.body.style.fontSize = * dpr + 'px';
} else {
doc.addEventListener('DOMContentLoaded', function(e) {
doc.body.style.fontSize = * dpr + 'px';
}, false);
} refreshRem(); flexible.dpr = win.dpr = dpr;
flexible.refreshRem = refreshRem;
flexible.rem2px = function(d) {
var val = parseFloat(d) * this.rem;
if (typeof d === 'string' && d.match(/rem$/)) {
val += 'px';
}
return val;
}
flexible.px2rem = function(d) {
var val = parseFloat(d) / this.rem;
if (typeof d === 'string' && d.match(/px$/)) {
val += 'rem';
}
return val;
} })(window, window['lib'] || (window['lib'] = {}));

用rem写1px 维护行方便;图片高度可以用rem固定高度,防止加载时出现高度自动网速加载慢导致的明显塌陷;   缺点: 动态控制  viewport  retina下,无论美团还是淘宝用 rem始终还有许多细小的问题;在ios上浏览器打开仔细看还是看的出的,安卓上没看出来;

有时候retina下, viewport  缩放动态控制字体大小;<meta name="viewport" content="initial-scale=0.5, maximum-scale=0.5, minimum-scale=0.5, user-scalable=no">  竖线或者奇数偶数行横线 或者动态添加显示的元素   之后的1px线条,有的1.1px  或者1.2px等等...拿手机仔细看下,观察iphone5 以及iphone6  safari以及其他浏览器对比下就知道,以下是截图出来问题的(只是示范一下 红色箭头的 border 线条 ),同样都是像素比 ratio=2  真机上细看还是明显的。

H5  Canvas  Retina屏幕处理的1px的函数

 /**
* HiDPI Canvas Polyfill (1.0.9)
*
* Author: Jonathan D. Johnson (http://jondavidjohn.com)
* Homepage: https://github.com/jondavidjohn/hidpi-canvas-polyfill
* Issue Tracker: https://github.com/jondavidjohn/hidpi-canvas-polyfill/issues
* License: Apache 2.0
*/
;(function(prototype) { var pixelRatio = (function(context) {
var backingStore = context.backingStorePixelRatio ||
context.webkitBackingStorePixelRatio ||
context.mozBackingStorePixelRatio ||
context.msBackingStorePixelRatio ||
context.oBackingStorePixelRatio ||
context.backingStorePixelRatio || ; return (window.devicePixelRatio || ) / backingStore;
})(prototype), forEach = function(obj, func) {
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
func(obj[p], p);
}
}
}, ratioArgs = {
'fillRect': 'all',
'clearRect': 'all',
'strokeRect': 'all',
'moveTo': 'all',
'lineTo': 'all',
'arc': [,,],
'arcTo': 'all',
'bezierCurveTo': 'all',
'isPointinPath': 'all',
'isPointinStroke': 'all',
'quadraticCurveTo': 'all',
'rect': 'all',
'translate': 'all',
'createRadialGradient': 'all',
'createLinearGradient': 'all'
}; if (pixelRatio === ) return; forEach(ratioArgs, function(value, key) {
prototype[key] = (function(_super) {
return function() {
var i, len,
args = Array.prototype.slice.call(arguments); if (value === 'all') {
args = args.map(function(a) {
return a * pixelRatio;
});
}
else if (Array.isArray(value)) {
for (i = , len = value.length; i < len; i++) {
args[value[i]] *= pixelRatio;
}
} return _super.apply(this, args);
};
})(prototype[key]);
}); // Stroke lineWidth adjustment
prototype.stroke = (function(_super) {
return function() {
this.lineWidth *= pixelRatio;
_super.apply(this, arguments);
this.lineWidth /= pixelRatio;
};
})(prototype.stroke); // Text
//
prototype.fillText = (function(_super) {
return function() {
var args = Array.prototype.slice.call(arguments); args[] *= pixelRatio; // x
args[] *= pixelRatio; // y this.font = this.font.replace(
/(\d+)(px|em|rem|pt)/g,
function(w, m, u) {
return (m * pixelRatio) + u;
}
); _super.apply(this, args); this.font = this.font.replace(
/(\d+)(px|em|rem|pt)/g,
function(w, m, u) {
return (m / pixelRatio) + u;
}
);
};
})(prototype.fillText); prototype.strokeText = (function(_super) {
return function() {
var args = Array.prototype.slice.call(arguments); args[] *= pixelRatio; // x
args[] *= pixelRatio; // y this.font = this.font.replace(
/(\d+)(px|em|rem|pt)/g,
function(w, m, u) {
return (m * pixelRatio) + u;
}
); _super.apply(this, args); this.font = this.font.replace(
/(\d+)(px|em|rem|pt)/g,
function(w, m, u) {
return (m / pixelRatio) + u;
}
);
};
})(prototype.strokeText);
})(CanvasRenderingContext2D.prototype);
;(function(prototype) {
prototype.getContext = (function(_super) {
return function(type) {
var backingStore, ratio,
context = _super.call(this, type); if (type === '2d') { backingStore = context.backingStorePixelRatio ||
context.webkitBackingStorePixelRatio ||
context.mozBackingStorePixelRatio ||
context.msBackingStorePixelRatio ||
context.oBackingStorePixelRatio ||
context.backingStorePixelRatio || ; ratio = (window.devicePixelRatio || ) / backingStore; if (ratio > ) {
this.style.height = this.height + 'px';
this.style.width = this.width + 'px';
this.width *= ratio;
this.height *= ratio;
}
} return context;
};
})(prototype.getContext);
})(HTMLCanvasElement.prototype);

viewport + REM的方式来实现:

在devicePixelRatio = 2 时,输出viewport

 <meta name="viewport" content="initial-scale=0.5, maximum-scale=0.5, minimum-scale=0.5, user-scalable=no">

在devicePixelRatio = 3 时,输出viewport

 <meta name="viewport" content="initial-scale=0.3333333333333333, maximum-scale=0.3333333333333333, minimum-scale=0.3333333333333333, user-scalable=no">

代码:

 <script type="text/javascript">
(function() {
var value=;
if (window.devicePixelRatio == ) {
value=0.5;
}else if(window.devicePixelRatio == ){
value=0.333333333333333;
}
var text = '<meta name="viewport" content="initial-scale=' + value + ', maximum-scale=' + value +', minimum-scale=' + value + ', width=device-width, user-scalable=no" />';
document.write(text);
})();
</script>

同时通过设置对应viewport的rem基准值,这种方式就可以像以前一样轻松愉快的写1px了。

需要使用rem,我们需要设置根的font-size。

移动端Retina屏boder 1px显示为2px或3px的解决方法的更多相关文章

  1. 移动端Retina屏边框线1px 显示为2px或3px问题解决方法

    我们在开发移动端web项目时经常遇到设置border:1px,但是显示的边框却为2px或是3px粗细,这是因为设备像素比devicePixelRatio为2或3引起的.   1.何为“设备像素比dev ...

  2. Retina屏实现1px边框

    问题描述 通常我们实现边框的方法都是设置1px的边框,但是在retina屏上因为设备像素比的不同,边框在移动设备上的表现也不相同,例如在devicePixelRatio = 2的retina屏下会显示 ...

  3. Retina屏下1px border

    layout tltle tags post ios7下移动web开发的几个坑 webapp 1.Retina屏下1px border 由于高清屏的特性,1px是由2×2个像素点来渲染,那么我们样式上 ...

  4. 移动端 Retina屏border实现0.5px

    首先来看一下造成Retina边框变粗的原因 其实这个原因很简单,因为css中的1px并不等于移动设备的1px,这些由于不同的手机有不同的像素密度.在window对象中有一个devicePixelRat ...

  5. webstorm无法显示左边文件夹目录的解决方法

    webstorm无法显示左边文件夹目录的解决方法 方法一 view-->Tool Windows-->Project 就可以显示或者关闭 方法二 1.删除webstorm的配置文件夹 2. ...

  6. Adobe Illustrator CS6 界面文字按钮太小,高分屏win10PS/AI等软件界面字太小解决方法

    Adobe Illustrator CS6 界面文字按钮太小,高分屏win10PS/AI等软件界面字太小解决方法 Adobe App Scaling on High DPI Displays (FIX ...

  7. 移动端 Retina屏 各大主流网站1px的解决方案

    Retina屏的移动设备如何实现真正1px的线? 在retina屏下面,如果你写了这样的meta <meta name="viewport" content="in ...

  8. 移动端前端笔记 — 遇到的常见JS与CSS问题及解决方法 ( 摘自zdwzdwzdw)

    笔者接触移动前端快一年了,特将平时的一些笔记整理出来,希望能够给需要的人一些小小的帮助.同时也由于笔者的水平有限,虽说都是笔者遇到过使用过的,但文中可能也会出现一些问题或不严谨的地方,望各位指出,不胜 ...

  9. windows桌面图标不显示,左右键无法使用的解决方法

    问题描述: 日常使用软件中,一返回桌面,桌面图标全部不显示,点击鼠标的左键,右键毫无反应 解决方法: 1. Ctrl+Shift+Esc呼出软仵管理器 2. 右键windows资管理器,点击属性 配图 ...

随机推荐

  1. PAT 在霍格沃茨找零钱

    如果你是哈利·波特迷,你会知道魔法世界有它自己的货币系统 —— 就如海格告诉哈利的:“十七个银西可(Sickle)兑一个加隆(Galleon),二十九个纳特(Knut)兑一个西可,很容易.”现在,给定 ...

  2. MySQL 8.0权限认证(下)

    MySQL 8.0权限认证(下)   一.设置MySQL用户资源限制   通过设置全局变量max_user_connections可以限制所有用户在同一时间连接MySQL实例的数量,但此参数无法对每个 ...

  3. Flask 四剑客

    Flask 四剑客 返回字符串,返回 html , 跳转路由,返回 json from flask import Flask, render_template, redirect, jsonify a ...

  4. centos7 和centos6 服务操作命令对比

    以httpd为例子: 指令名称 centos 6 centos 7 启动服务 service httpd start systemctl start httpd.service 关闭服务 servic ...

  5. 完美解决PYQT5登录界面跳转主界面方法

    该问题,有很多种方法,但是很多方法要么这个有问题,要么那个有问题,最后终于找到一种没问题的方法.记录一下: Login.py(登录窗口)文件 import sys from PyQt5 import ...

  6. skfpdb.db、cc3268.dll、system_V2.dat、JI60JS.dat文件内容、发票数据查询

    cc3268.dll.skfpdb.db.xxxxx_V2.dat,system.dat,JI60JS.dat,log.dat,system_V2.dat,JI60JS_V2.dat,log_V2.d ...

  7. linux环境下安装git(采用github下载git源码编译)

    [目的]:linux环境下 安装配置git成功 [准备条件]linux系统,git包 1.先行下载git包 -- 从github上https://github.com/git/git/releases ...

  8. Github删除分支下所有提交记录

    [本文版权归微信公众号"代码艺术"(ID:onblog)所有,若是转载请务必保留本段原创声明,违者必究.若是文章有不足之处,欢迎关注微信公众号私信与我进行交流!] 有时候,我们提交 ...

  9. 僵尸扫描-scapy、nmap

    如果不知道僵尸扫描是什么,请参考我的这篇博客 实验环境: kali(攻击者) 192.168.0.103 metasploitable2(目标主机) 192.168.0.104 win xp sp2( ...

  10. Python三大器之生成器

    Python三大器之生成器 生成器初识 什么是生成器 生成器本身属于迭代器.继承了迭代器的特性,惰性求值,占用内存空间极小. 为什么要有生成器 我们想使用迭代器本身惰性求值的特点创建出一个可以容纳百万 ...