一些不错的js片段值得参考学习

Posted by Turingdo Studio on June 7, 2016

片段1

function canUseDom () {
	return !!(
		typeof window !== 'undefined'
		&& window.document
		&& window.document.createElement
	);
};

片段2

import MobileDetect from 'mobile-detect';
const md = new MobileDetect(window.navigator.userAgent);

module.exports = {
  iOSVer: md.version('iOS') ? md.version('iOS') : null,
  androidVer : md.version('Android') ? md.version('Android') : null,
  isIOS : md.os() === 'iOS',
  isIOS8 : md.os() === 'iOS' && parseFloat(md.version('iOS')) >= 8 && parseFloat(md.version('iOS')) < 9,
  isIOS9 : md.os() === 'iOS' && parseFloat(md.version('iOS')) >= 9 && parseFloat(md.version('iOS')) < 10,
  isIOS10 : md.os() === 'iOS' && parseFloat(md.version('iOS')) >= 10 && parseFloat(md.version('iOS')) < 11,
  isAndroid : md.os() === 'AndroidOS',
  isWindow: md.os() === 'WindowsMobileOS' || md.os() === 'WindowsPhoneOS',
  isMobile: md.mobile() !== null ? true : false,
  isWechat: md.match('MicroMessenger') ? true : false,
  wechatVer: md.version('MicroMessenger') ? md.version('MicroMessenger') : null,
};

片段3

import React from 'react';
import classNames from 'classnames';
import './toptips.less';

/**
 *  Drop down message from top
 *
 */
const Toptips = (props) => {
    const {className, type, children, show, ...others} = props;
    const cls = classNames({
        'weui-toptips': true,
        [`weui-toptips_${type}`]: true,
        [className]: className
    });

    return (
        <div className={cls} {...others} style=>
            {children}
        </div>
    );
};

Toptips.propTypes = {
    /**
     * display tips
     *
     */
    show: React.PropTypes.bool,
    /**
     * type: `default`, `warn`, `info`, `primary`
     */
    type: React.PropTypes.string
};

片段4

import React from 'react';
import classNames from 'classnames';

/**
 * WeUI Label Wrapper
 *
 */
 //无状态组件
const Label = (props) => {
    const { className, ...others } = props;
    const cls = classNames({
        'weui-label': true,
        [className]: className
    });

    return (
        <div>
            <label className={cls} {...others}/>
        </div>
    );
};

export default Label

片段5

function androidInputBugFix(){
        // .container 设置了 overflow 属性, 导致 Android 手机下输入框获取焦点时, 输入法挡住输入框的 bug
        // 相关 issue: https://github.com/weui/weui/issues/15
        // 解决方法:
        // 0. .container 去掉 overflow 属性, 但此 demo 下会引发别的问题
        // 1. 参考 http://stackoverflow.com/questions/23757345/android-does-not-correctly-scroll-on-input-focus-if-not-body-element
        //    Android 手机下, input 或 textarea 元素聚焦时, 主动滚一把
        if (/Android/gi.test(navigator.userAgent)) {
            window.addEventListener('resize', function () {
                if (document.activeElement.tagName == 'INPUT' || document.activeElement.tagName == 'TEXTAREA') {
                    window.setTimeout(function () {
                        document.activeElement.scrollIntoViewIfNeeded();
                    }, 0);
                }
            })
        }
    }

片段6 淘宝前端——React 组件间通讯 ``` // eventProxy.js ‘use strict’; const eventProxy = { onObj: {}, oneObj: {}, on: function(key, fn) { if(this.onObj[key] === undefined) { this.onObj[key] = []; }

this.onObj[key].push(fn);   },   one: function(key, fn) {
if(this.oneObj[key] === undefined) {
  this.oneObj[key] = [];
}

this.oneObj[key].push(fn);   },   off: function(key) {
this.onObj[key] = [];
this.oneObj[key] = [];   },   trigger: function() {
let key, args;
if(arguments.length == 0) {
  return false;
}
key = arguments[0];
args = [].concat(Array.prototype.slice.call(arguments, 1));

if(this.onObj[key] !== undefined
  && this.onObj[key].length > 0) {
  for(let i in this.onObj[key]) {
    this.onObj[key][i].apply(null, args);
  }
}
if(this.oneObj[key] !== undefined
  && this.oneObj[key].length > 0) {
  for(let i in this.oneObj[key]) {
    this.oneObj[key][i].apply(null, args);
    this.oneObj[key][i] = undefined;
  }
  this.oneObj[key] = [];
}   } };

export default eventProxy;

eventProxy 中,总共有 on、one、off、trigger 这 4 个函数:

on、one:on 与 one 函数用于订阅者监听相应的事件,并将事件响应时的函数作为参数,on 与 one 的唯一区别就是,使用 one 进行订阅的函数,只会触发一次,而 使用 on 进行订阅的函数,每次事件发生相应时都会被触发。

trigger:trigger 用于发布者发布事件,将除第一参数(事件名)的其他参数,作为新的参数,触发使用 one 与 on 进行订阅的函数。

off:用于解除所有订阅了某个事件的所有函数。

> 片段 7 requestAnimationFrame 动画
[requestAnimationFrame 动画](http://www.cnblogs.com/Wayou/p/requestAnimationFrame.html)

function fadeIn(ele) { var animaFram = function (ele) {

    var opacity = 0
    return function step() {
        opacity += .1;
        ele.style.opacity = opacity;
        if (opacity < .9) {
            requestAnimationFrame(step)
        }
    }
}
requestAnimationFrame(animaFram(ele)) }

function fadeOut(ele) { var animaFram = function (ele) {

    var opacity = 0
    return function step() {
        opacity -= .1;
        ele.style.opacity = opacity;
        if (opacity > 0) {
            requestAnimationFrame(step)
        }
    }
}
requestAnimationFrame(animaFram(ele)) } ```