Loading

每日思考(2020/08/11)

题目概览

  • 用HTML5实现手机摇一摇功能的原理
  • 遇到过IE6/7/8/9的BUG及解决方法
  • 用js实现一个九九乘法口诀表

题目解答

用HTML5实现手机摇一摇功能的原理

  • 原理:以100ms的间隔去扫描加速度计,当检测到加速度发生突变(变化率大于阀值)时,就可以认为此时在甩动手机。由公式可以看到,这里检测的是3个方向的加速度,所以无论往什么方向甩都可以触发摇一摇效果

  • 核心代码

    this.deviceMotionHandler = function(eventData) {        
        var acceleration = eventData.acceleration;   
        var curTime = new Date().getTime();         
        //检测频率:每100ms一次
        if ((curTime - that.last_update) > 100) {     
            var diffTime = curTime - that.last_update;      
            that.last_update = curTime;     
            that.x = acceleration.x;            
            that.y = acceleration.y;         
            that.z = acceleration.z;      
            var speed = Math.abs(that.x + that.y + that.z - that.last_x - that.last_y - that.last_z) / diffTime * 10000;            
            if (speed > that.SHAKE_THRESHOLD) {  
                //do something
                that.shakeAudio.play();        //摇一摇音效
                window.navigator.vibrate(200);    //振动效果
                that.shakeEffect.className = 'shake-box shaking';    //摇一摇图片动态
                clearTimeout(shakeTimeout);         
                var shakeTimeout = setTimeout(function() {
                    that.shakeEffect.className = 'shake-box';
                },4000);           
            }    
            that.last_x = that.x;      
            that.last_y = that.y;               
            that.last_z = that.z;         
        }        
    };
    

遇到过IE6/7/8/9的BUG及解决方法

用js实现一个九九乘法口诀表

/**
 * print 打印乘法表
 * @param {number} length :字符串
 * @return {string}
 */
function print(length) {
    const MAX_WIDTH = 7
    let table = ''
    for (let rhs = 1; rhs <= length; rhs++) {
        for (let lhs = 1; lhs <= length; lhs++) {
            if (lhs <= rhs) table += `${lhs}*${rhs}=${lhs * rhs}`.padEnd(MAX_WIDTH)
        }
        table += '\n'
    }
    return table
}

let reStr = print(9);
console.log(reStr); 
posted @ 2020-08-12 00:11  澎湃_L  阅读(114)  评论(0编辑  收藏  举报