ONE-SUNDAY / Blog

6 stars 0 forks source link

移动端小技巧(持续更新) #1

Open ONE-SUNDAY opened 8 years ago

ONE-SUNDAY commented 8 years ago

工作中常用的一些技巧,放在这里,没有特意归类,请随意。

使用 sticky 属性的情况下,父元素不能有 overflow : hidden

否则会导致 sticky 失效

iOS rotate 360deg 动画,不要 0deg - 360deg

中间间隔 180deg

transition 不要用 all

针对用到的缓动属性去定义,不要一股脑的 all ,那样会带来一些不必要的麻烦

判断当前网络情况

占位

开发技巧

https://juejin.im/entry/58f6d9fb44d904006c121d2e

单词太长自动换行问题

https://juejin.im/post/58f5ead2570c3500564a5c57

右侧固定左边内容超出隐藏

占位

聊聊 input file - 文件上传

https://github.com/Monine/study/issues/5

插入音乐

var url = "images/song.mp3";
window.audio = document.createElement("audio");
var source = document.createElement("source");
audio.id = "audio";
source.type = "audio/mpeg";
source.src = url;
source.autoplay = "autoplay";
// 音乐循环
audio.addEventListener("ended", function() {
    audio.play();
}, false);

audio.appendChild(source);
audio.play();

计算两点的距离

var x1 = eval(form.x1.value);
var y1 = eval(form.y1.value);
var x2 = eval(form.x2.value);
var y2 = eval(form.y2.value);
var xdiff = x2 - x1;
var ydiff = y2 - y1;
form.answer.value = Math.pow((xdiff * xdiff + ydiff * ydiff), 0.5);

CCS3 实现平形四边形

占位

宽高长图片自适应布局

/* 判断图片宽高,分开处理 */
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
&.w {
  width: 100%;
  height: auto;
}
&.h {
  width: auto;
  height: 100%;
}

icon font VS inline SVG

新趋势:使用 SVG 替代 icon font 使用 SVG 中的 Symbol 元素制作 icon

iOS 下避免吸顶元素有输入框

这会导致在弹出输入框滑动屏幕时,吸顶元素会表现的像 absolute,导致错位。

iOS sticky 吸顶

占位

input标签输入时光标不居中问题

解决方案是不要给 <input> 标签加 line-height 属性

反驳:不完美,对于 placeholder 属性的文字,并不居中。

设置 height 和 line-height 为相同值时,在 Android 无法垂直居中

::before {
    content: '';
    display: inline-block;
    vertical-align: middle;
    width: 0;
    height: 100%;
    margin-top: 1px;
}

关于 Android 微信 X5 查某个属性支持度

iOS系统微信使用的是 Safari 的内核,查支持度到 Can I use 即可。

Android 则不同,还得看 X5 的脾气,所以以下是查支持度的步骤:

iOS / Android 微信 Video 白名单与非白名单下的表现

占坑

修改 iPhone Safari 下 input disabled 的颜色

input:disabled {
    -webkit-text-fill-color: #ddd;
}

fit-content 不定宽元素居中

居中的两种旧方式:一是定宽度加 margin: 0 auto、二是外层 text-align: center; 里层 display: inline-block;

<div class="more_btn">查看更多</div>
.more_btn {
    margin: auto;
    padding: 0 30px;
    width: -webkit-fit-content;
    width: fit-content; /* 第三种方法 */
    height: 40px;
    line-height: 40px;
    background: #4caf50;
    color: #fff;
    font-size: 14px;
    text-align: center;
    border-radius: 4px;
}

DEMO 点击这里

1px边框

/* full */
.border_full::before {
    content: '';
    position: absolute;
    z-index: 1;
    pointer-events: none;
    border: 1px solid #ddd;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
}
@media only screen and (-webkit-min-device-pixel-ratio:2) {
    .border_full::before {
        right: -100%;
        bottom: -100%;
        -webkit-transform: scale(0.5);
        transform: scale(0.5);
    }
}

/* top */
.border_top::before {
    content: '';
    position: absolute;
    z-index: 1;
    pointer-events: none;
    background: #ddd;
    height: 1px;
    left: 0;
    right: 0;
    top: 0;
}
@media only screen and (-webkit-min-device-pixel-ratio:2) {
    .border_top::before {
        -webkit-transform: scaleY(0.5);
        -webkit-transform-origin: 50% 0%;
    }
}

/* bottom */
.border_bottom::before {
    content: '';
    position: absolute;
    z-index: 1;
    pointer-events: none;
    background: #ddd;
    height: 1px;
    left: 0;
    right: 0;
    bottom: 0;
}
@media only screen and (-webkit-min-device-pixel-ratio:2) {
    .border_bottom::before {
        -webkit-transform: scaleY(0.5);
        -webkit-transform-origin: 50% 100%;
    }
}

/* left */
.border_left::before {
    content: '';
    position: absolute;
    z-index: 1;
    pointer-events: none;
    background: #ddd;
    width: 1px;
    top: 0;
    left: 0;
    bottom: 0;
}
@media only screen and (-webkit-min-device-pixel-ratio:2) {
    .border_left::before {
        -webkit-transform: scaleX(0.5);
        -webkit-transform-origin: 0% 50%;
    }
}

/* right */
.border_left::before {
    content: '';
    position: absolute;
    z-index: 1;
    pointer-events: none;
    background: #ddd;
    width: 1px;
    top: 0;
    right: 0;
    bottom: 0;
}
@media only screen and (-webkit-min-device-pixel-ratio:2) {
    .border_left::before {
        -webkit-transform: scaleX(0.5);
        -webkit-transform-origin: 100% 50%;
    }
}

appearance取消默认样式

/* 去掉date类型input的叉叉 */
::-webkit-clear-button {
    -webkit-appearance: none; 
}

/* 去掉number类型的上下箭头 */
::-webkit-inner-spin-button {
     -webkit-appearance: none;
}

/* 去除圆角 */
input[type=search] {
    -webkit-appearance: none;
}

/* 隐藏取消按钮 */
::-webkit-search-cancel-button {
    -webkit-appearance: none;
}

/* 隐藏放大镜 */
::-webkit-search-results-button {
    -webkit-appearance: none;
}

SVG实现环形进度条

实现环形进度条需要使用到SVG中的路径<path>

在写代码之前,首先了解<path>有哪些参数

M

表示坐标的起点

未完...

参考资料:https://developer.mozilla.org/zh-CN/docs/Web/SVG/Tutorial/Paths

SVG实现飘带文字

<svg xmlns="http://www.w3.org/2000/svg" version="1.1"
xmlns:xlink="http://www.w3.org/1999/xlink" viewbox="0, 0, 332, 48" width="400" height="300" style="border: 1px solid #000">
    <path id="textPath" d="m0.749997,39.860256c92.99817,20.99958 250.99507,-15.99969 327.99356,1.99996" opacity="0.5" stroke-opacity="null" stroke-width="1" stroke="none" fill="none"></path>
    <text fill="#000" font-size="28" x="0" y="0">
        <textPath xlink:href="#textPath" text-anchor="middle" startOffset="50%">
            利益点利益点利益点
        </textPath>
    </text>
</svg>

viewbox属性用于缩放,具体效果可参考:理解SVG的viewport,viewBox,preserveAspectRatio <path>则是绘制文件的路径,可通过Adobe AI导出 <text>则是定义文本,<textPath>绘制路径上的文字 当viewbox没有设置宽度时,根据上一层宽高进行缩放

DEMO点击这里

渐变文字与镂空文字

<p class="gradient_txt">渐变文字渐变文字渐变文字渐变文字</p>
<p class="hollow_txt">镂空文字镂空文字镂空文字镂空文字</p>  
.gradient_txt {
    background-color: #890ffa;
    background-image: gradient(linear, left top, right top, from(#890ffa), to(#d80078));
    background-clip: text;
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
}

.hollow_txt {
    font-size: 50px;
    -webkit-text-stroke: 1px #000;
    -webkit-text-fill-color: transparent;
}

镂空文字对较小的文字不友善,目前未有较好的办法

DEMO点击这里

去掉倒数几个元素

&:not(:nth-last-child(-n+4)) { // 除了倒数4个
    margin-bottom: 10px;
}

去掉最后一个元素的某个属性

比如给一列的<li>元素加margin-bottom: 10px;最后一个为margin-bottom: 0;

/* 常规写法 */
li {
    width: 100px;
    height: 100px;
    margin-bottom: 10px;
}
li:last-child {
   margin-bottom: 0;
}
/* 推荐写法 */
li {
    width: 100px;
    height: 100px;
}
li:not(:last-child) {
   margin-bottom: 10px;
}

好处在于不需要覆盖原属性值达到效果

iOS视频内嵌,不全屏播放

<video webkit-playsinline src="video.mp4"></video>

关于Android内嵌视频目前仅在腾讯域名白名单下才能较好的运行 另外推荐iphone-inline-video库,实现iOS内嵌视频并且隐藏iOS视频的播放暂停按钮

隐藏iOS视频的播放暂停按钮

video::-webkit-media-controls-play-button,
video::-webkit-media-controls-start-playback-button {
    opacity: 0;
    pointer-events: none;
    width: 5px;
}

判断浏览器是否支持WebP

(function() {
    var img = new Image();
    img.onload = function() {
        if (img.width > 0 && img.height > 0) {
            document.documentElement.className = "webp";
            window.webpSupport = true;
        }
    }
    img.onerror = function() {}
    img.src = "data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA";
}());

判断浏览器是否支持APNG

(function() {
    "use strict";
    var apngTest = new Image(),
    ctx = document.createElement("canvas").getContext("2d");
    apngTest.onload = function () {
        ctx.drawImage(apngTest, 0, 0);
        self.apng_supported = ctx.getImageData(0, 0, 1, 1).data[3] === 0;
    };
    apngTest.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACGFjVEwAAAABAAAAAcMq2TYAAAANSURBVAiZY2BgYPgPAAEEAQB9ssjfAAAAGmZjVEwAAAAAAAAAAQAAAAEAAAAAAAAAAAD6A+gBAbNU+2sAAAARZmRBVAAAAAEImWNgYGBgAAAABQAB6MzFdgAAAABJRU5ErkJggg==";
}());

不支持的浏览器则在getImageData(0, 0, 1, 1).data[3]获取alpha通道会返回[0, 0, 0, 255]; 支持的浏览器则返回[0, 0, 0, 0];

@supports 根据浏览器对CSS3特性的支持情况来定义不同样式

/* 当浏览器支持弹性布局,括号内的样式生效 */
@supports (display: flex) {
    .example {
        display: flex;
    }
}
/* 当浏览器不支持弹性布局,括号内的样式生效 */
@supports not (display: flex) {
    .example {
        float: left;
    }
}
/* 与或判断 */
@supports ((display: -webkit-flex) or 
    (display: -moz-flex) or
    (display: flex)) and (-webkit-appearance: caret) {
    /* use styles here */
}
// JavaScript中提供了window.CSS.supports方法
// 第一种方法
var supportsFlex = CSS.supports("display", "flex");
// 第二种方法
var supportsFlexAndAppearance = CSS.supports("(display: flex) and (-webkit-appearance: caret)");

隐藏滚动条

.example::-webkit-scrollbar {
    width: 0;
    height:0;
    display: none;
}

弹性滚动

/* 目前仅支持iOS */
.example {
    -webkit-overflow-scrolling: touch;
}

自定义滚动条

.example::-webkit-scrollbar { 
    width: 6px;
    height: 4px;
}
.example::-webkit-scrollbar-button {
    width: 0;
    height: 0;
}
.example::-webkit-scrollbar-corner {
    display: block;
}
.example::-webkit-scrollbar-thumb {
    background-clip: padding-box;
    background-color: #ffffff;
}

CSS3滤镜

.example-1 {
    -webkit-filter: blur(5px); /* 毛玻璃 */
}

.example-2 {
    -webkit-filter: grayscale(0.5); /* 灰度 */
}

.example-3 {
    -webkit-filter: sepia(0.5); /* 褐色 */
}

.example-4 {
    -webkit-filter: brightness(3); /* 亮度 */
}

.example-5 {
    -webkit-filter: hue-rotate(180deg); /* 色相 */
}

.example-6 {
    -webkit-filter: invert(1); /* 反色 */
}

.example-7 {
    -webkit-filter: opacity(0.5); /* 透明度 */
}

.example-8 {
    -webkit-filter: saturate(5); /* 饱和度 */
}

.example-9 {
    -webkit-filter: contrast(0.5); /* 对比度 */
}

.example-10 {
    -webkit-filter: drop-shadow(10px 10px 5px rgba(0, 0, 0, 0.9)); /* 阴影 */
}

DEMO点击这里

单行文字超出省略号

.example {
    width: 200px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-scaple: nowrap;
}

多行文字超出省略号

.example {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2; /* 溢出超过2行省略号 */
    text-overflow: ellipsis;
    overflow: hidden;
}

user-select属性

.example {
    user-select: none; /* 禁止选择 */
    user-select: auto; /* 浏览器来决定是否允许选择 */
    user-select: all; /* 可以选择任何内容 */
    user-select: text; /* 只能选择文本 */
    user-select: contain; /* 选择绑定的元素以内的内容 */
}

两列 左固定右内容垂直居中

方法一:高度无限制

<div class="box">
    <div class="left">
        <img src="http://fpoimg.com/100x100">
    </div>
    <div class="right">文字</div>
</div>
.box {
    display: -webkit-box; /* 2009年的语法 */
    display: box;
    -webkit-box-align: center;  /* 垂直居中 */
    box-align: center;
    display: -webkit-flex; /* 2012年的语法 */
    display: flex;
    -webkit-align-items: center; /* 垂直居中 */
    align-items: center;
}
.left {
    width: 100px;
    height: 100px;
}
.right {
    -webkit-box-flex: 1;
    box-flex: 1;
    -webkit-flex: 1;
    flex: 1;
}

方法二:高度有限制

<div class="box">
    <div class="left">
        <img src="http://fpoimg.com/100x100">
    </div>
    <div class="right">
        <div class="info">
            <p>文字</p>
            <p>文字</p>
            <p>文字</p>
            <p>文字</p>
            <p>文字</p>
            <p>文字</p>
        </div>
    </div>
</div>
.box {
    position: relative;
}
.left {
    position: absolute;
    top: 0;
    left: 0;
}
.right {
    position: relative;
    margin-left: 100px;
    font-size: 0;
    overflow: hidden;
}
.right:before {
    content: '';
    display: inline-block;
    width: 0;
    min-height: 100px;
    vertical-align: middle;
}
.right .info {
    position: relative;
    display: inline-block;
    vertical-align: middle;
    font-size: 12px;;
}

DEMO1点击这里 DEMO2点击这里

calc()允许简单的加、减、乘、除运算

<ul class="col-3">
    <li></li>
    <li></li>
    <li></li>
</ul>
.col-3 {
    width: 200px;
    height: 200px;
}
.clo-3 li {
    float: left;
    width: calc(100% / 3); /* 33.3% */
    height: 200px;
}

判断用户手机旋屏

/* 方法一 */
/* 竖屏 */
@media all and (orientation: portrait) { /* 规定显示设备的取向 */
    .example {
        display: block;
    }
}

/* 横屏 */
@media all and (orientation: landscape) { /* 规定显示设备的取向 */
    .example {
        display: none;
    }
}

/* 方法二 */
/* 横屏 */
@media screen and (min-aspect-ratio: 13/9) { /* 规定显示设备区域的宽度/高度比 */
    .example {
        display: block;
    }
}
/* 方法三 */
function checkDirect() {
    // 横屏
    if (window.orientation == 180 || window.orientation == 0) {
        document.querySelector(".example").style.display = "block";
    }
    // 竖屏
    if (window.orientation == 90 || window.orientation == -90) {
        document.querySelector(".example").style.display = "none";
    }
}
checkDirect();
window.addEventListener("onorientationchange" in window ? "orientationchange" : "resize", checkDirect, false);

设置input标签placeholder属性的样式

.example::-webkit-input-placeholder {
    color: red;
}

取消点击a、button、input标签后区域半透明遮罩

a, button, input {
    -webkit-tap-highlight-color: rgba(255,0,0,0);
}

使用Chrome模拟手机调试时字体太大

Google Chrome默认浏览器字体最小字体为:12px,而我们手机端页面常常字体小于12px。 解决:右上角(自定义及控制) -> 设置 -> 显示高级设置 -> 网络内容(自定义字体) -> 最小字号(最小可以设置为6px)

监听CSS3动画事件

/* 
动画开始事件:webkitAnimationStart
动画结束事件:webkitAnimationEnd
动画循环事件:webkitAnimationIteration
过渡动画结束事件:webkitTransitionEnd
 */
example.addEventListener("webkitAnimationStart", function() {
    console.log("动画开始"); // 动画开始执行一次
}, false);

example.addEventListener("webkitAnimationIteration", function() {
    console.log("动画循环结束"); // 动画每循环完成一次执行一次
}, false);

判断用户是否在手机端

if (/Android|Windows Phone|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
    window.location.href = "http://www.example.com";
}

图片水平镜像反转

.example-1 {
    transform: scaleX(-1); /* 方法一 */
}
.example-2 {
    transform: rotateY(180deg); /* 方法二 */
}

自旋转动画

<div class="example"></div>
.example {
    position: absolute;
    top: 200px;
    left: 200px;
    width: 100px;
    height: 100px;
    border: 2px solid #000;
    border-radius: 50%;
    animation: autogyRation 4s linear infinite;
}

@keyframes autogyRation {
    from {
        transform: rotate(0deg) translate(-60px) rotate(0deg);
    }
    to {
        transform: rotate(360deg) translate(-60deg) rotate(-360deg);
    }
}

DEMO

扫光动画

<div class="example">
    <i></i>
</div>
.example {
    position: relative;
    width: 400px;
    height: 200px;
    background: #000;
    overflow: hidden;
}

.example i {
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    -webkit-transform: skewx(-25deg);
    transform: skewx(-25deg);
    background-image: -webkit-linear-gradient(0deg, rgba(255, 255, 255, 0), rgba(255, 255, 255, .5), rgba(255, 255, 255, 0));
}

.example:hover i {
    left: 100%;
    -webkit-transition: .8s;
    transition: .8s;
}

DEMO

监测手机晃动事件

// 晃动函数
function init() {
    if (window.DeviceMotionEvent) {
        window.addEventListener("devicemotion", deviceMotionHandler, false);
    } else {
        alert("您的手机不支持晃动事件");
    }
};
init();

// 定义一个摇动的阀值
var SHAKE_THRESHOLD = 1000;
// 定义一个变量保存上次更新的时间
var last_update = 0;
// 紧接着定义x、y、z记录三个轴的数据以及上一次出发的时间
var x;
var y;
var z;
var last_x;
var last_y;
var last_z;

function deviceMotionHandler(eventData) {
    // 获取含重力的加速度
    var acceleration = eventData.accelerationIncludingGravity;

    // 获取当前时间
    var curTime = new Date().getTime();
    var diffTime = curTime - last_update;

    // 固定时间段
    if (diffTime > 100) {
        last_update = curTime;

        x = acceleration.x;
        y = acceleration.y;
        z = acceleration.z;

        var speed = Math.abs(x + y + z - last_x - last_y - last_z) / diffTime * 10000;

        if (speed > SHAKE_THRESHOLD) {
            // TODO: 在此处可以实现晃动之后所要进行的操作
        }

        last_x = x;
        last_y = y;
        last_z = z;
    }
}

穿透属性

当元素叠在一起时,需要触发下层的元素时,给上层的元素加该属性。

.example {
    pointer-event: none;
}

开启GPU加速

  • HTML5 Video
  • transition和animation
  • transform-style: preserve-3d; transform: translate3d(0, 0, 0);
  • transform: translateZ(0px);

    使:active生效

  • will-change
<body ontouchstart="">

禁用自动识别页面中的电话号码

<meta name="format-detection" content="telephone=no">

UA

// iOS微信内置浏览器UA
Mozilla/5.0 (iPhone; CPU iPhone OS 7_1_2 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Mobile/11D257 MicroMessenger/6.0.1 NetType/WIFI

// Android微信内置浏览器UA
Mozilla/5.0 (Linux; Android 5.0; SM-N9100 Build/LRX21V) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/37.0.0.0 Mobile Safari/537.36 MicroMessenger/6.0.2.56_r958800.520 NetType/WIFI

// Android内置QQ浏览器UA
Mozilla/5.0 (Linux; Android 5.0; SM-N9100 Build/LRX21V) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/37.0.0.0 Mobile Safari/537.36 V1_AND_SQ_5.3.1_196_YYB_D QQ/5.3.1.2335 NetType/WIFI

// iOS内置QQ浏览器UA
Mozilla/5.0 (iPhone; CPU iPhone OS 7_1_2 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Mobile/11D257 QQ/5.2.1.302 NetType/WIFI Mem/28

取消按钮、输入框、选择框等默认风格

.example {
    appearance: none;
}

音频事件触发顺序

canplay -> play -> playing -> canplaythrough -> pause -> suspend -> ended

音频Sprite

audio.currentTime();

hash

<script type="text/html">

</script>
var template = document.querySelectorAll('script[type="text/html"]');
var showTemplate = function() {
    var _fun = function() {
    var hash = location.hash,
        index = parseInt(hash.replace('#', '')) || 0;
        document.body.innerHTML = template[index].innerHTML;
        if (document.body.childNodes[1].nodeType == 8) {
            document.title = document.body.childNodes[1].nodeValue;
        }
    };
    _fun(); //自己执行一次
    return _fun;
}();
    window.addEventListener('hashchange', function() {
        showTemplate();
    });

跑马灯

(function() {

            var speed = 3000;

            var _transitionEnd = "onwebkittransitionend" in window ? "webkitTransitionEnd" : "transitionend";

            var DOM_inner = document.querySelector(".comm_top_rolling .rolling_inner"),
                hidedom = null;

            DOM_inner.addEventListener(_transitionEnd,swich);

            function move() {
                hidedom = document.querySelector(".comm_top_rolling .rolling_row");
                var moveY = hidedom.getBoundingClientRect().height;
                DOM_inner.style.transition = "transform 0.5s";
                DOM_inner.style.webkitTransition = "transform 0.5s";
                DOM_inner.style.transform = "translate3d(0, -"+ moveY +"px, 0)";
                DOM_inner.style.webkitTransform = "translate3d(0, -"+ moveY +"px, 0)";
            }

            function swich() {
                DOM_inner.style.transition = "none";
                DOM_inner.style.webkitTransition = "none";
                DOM_inner.style.transform = "translate3d(0, 0, 0)";
                DOM_inner.style.webkitTransform = "translate3d(0, 0, 0)";
                DOM_inner.removeChild(hidedom);
                DOM_inner.appendChild(hidedom);
            }

            setInterval(move, speed);

        })();

插入DOM节点

在此前我们常用innerHTML,推荐一个比较冷门但很实用的方法insertAdjacentHTML和insertAdjacentText

element.insertAdjacentHTML(position, text);
element.insertAdjacentText(position, element);

beforebegin 在 element 元素的前面。 afterbegin 在 element 元素的第一个子节点前面。 beforeend 在 element 元素的最后一个子节点后面。 afterend 在 element 元素的后面。