设为首页 - 加入收藏 ASP站长网(Aspzz.Cn)- 科技、建站、经验、云计算、5G、大数据,站长网!
热搜: 创业者 数据 手机
当前位置: 首页 > 站长学院 > MySql教程 > 正文

html5 分层屏幕适配的方法(3)

发布时间:2020-05-11 23:20 所属栏目:115 来源:站长网
导读:!doctype htmlhtmlbodystylediv { position: absolute; width: 50.37037037037037%; /* w3 = w/v*u 其中 w = 544,v = 1080 */ height: 7.395833333333333%; /* h3 = h/g*f 其中 h = 142,g = 1920 */ background:

<!doctype html> <html> <body> <style> div { position: absolute; width: 50.37037037037037%; /* w3 = w/v*u 其中 w = 544,v = 1080 */ height: 7.395833333333333%; /* h3 = h/g*f 其中 h = 142,g = 1920 */ background: url() no-repeat; /* 背景图做元素 */ background-size: cover; left: 25.64814814814815%; /* x3 = x/v*u 其中 x = 277, v = 1080 */ top: 78.02083333333333%; /* y3 = y/g*f 其中 y = 1498, g = 1920 */ background-position-x: -48.34558823529412%; /* o = (x - m*v)/w 其中 m = .5 , v = 1080,x = 277,w = 544*/ background-position-y: 378.8732394366197%; /* p = (y - n*g)/h 其中 n = .5 , g = 1920,y = 1498,h = 142*/ } </style> <div></div> <!-- 容器 --> </body> </html>

<svg> 实现示例

preserveAspectRatio 的 meetOrSlice 为 meet 时对应 contain 适配。

preserveAspectRatio 的 meetOrSlice 为 slice 时对应 cover 适配。

preserveAspectRatio 值为 none 时对应 fill 适配。

这里 preserveAspectRatio 的 meetOrSlice 相对的是容器,不是 适配区 这里用 transform 来定位,而 preserveAspectRatio 的 meetOrSlice 固定为 xMinYMin。

<!doctype html> <html> <body> <style> svg { position: absolute; width: 50.37037037037037%; height: 7.395833333333333%; /* x4 = m*v/w*w3 + (x - m*v)/w*w1 */ /* y4 = n*g/h*h3 + (y - n*g)/h*h1 */ top: 0; left: 0; transform: translateX(99.26470588235294%) /* m*v/w*w3 其中 m = .5,v = 1080,w = 544 */ translateY(676.056338028169%); /* n*g/h*h3 其中 n = .5,g = 1920,h = 142 */ overflow: visible; } svg image { transform: translateX(-48.34558823529412%) /* (x - m*v)/w*w1 其中 x = 277,m = .5,v = 1080,w = 544 */ translateY(378.8732394366197%); /* (y - n*g)/h*h1 其中 y = 1498,n = .5,g = 1920,h = 142 */ } </style> <svg viewBox="0 0 544 142" preserveAspectRatio="xMinYMin meet"> <!-- 容器 --> <image width="544" height="142" xlink:href=http://www.jb51.net/html5/"http:/ui.qzone.com/544x142"/> <!-- 元素 --> </svg> </body> </html>

辅助工具

手动计算百分比及写 css 很麻烦,可以借助 sass 等工具来辅助简化。
设计稿宽 v 高 g 一般是页面级常量。
只需读取设计稿里每个 元素 的横坐标 x 、纵坐标 y 、宽 w 和 高 h,然后工具生成 css 即可。
这下妈妈再也不用担心我还原问题、屏幕适配问题了。

文字处理

文字固定或单行不固定,svg 的 text 标签可以处理

文字固定或单行不固定还可以将文字转为图片

文字多行不固定,可以借助 svg 的 foreignObject 嵌入普通 div

方案对比

屏幕适配方案非常多,选哪种方式实现 整层适配 或 精简适配,下面是对比

方案 缩放 定位 文字缩放 兼容
padding-top 百分比   只能依宽   ✓   ✗   ✓  
viewport   ✓   ✗   ✓   支持情况复杂  
object-fit   ✓   ✓   ✗   移动端 android 4.4.4+  
svg preserveRatio   ✓   ✓   ✓   移动端 android 3.0+  
(max/min)-(width/height)   ✓   ✓   固定文字   ✓  
background-size   ✓   ✓   文字转图片   ✓  

(编辑:ASP站长网)

网友评论
推荐文章
    热点阅读