前端日常问题记录

1、react执行webpack打包后打开html空白页问题
替换BrowserRouter为HashRouter

import { BrowserRouter as Router, Route, Redirect, Link, Switch } from "react-router-dom";

import { HashRouter as Router, Route, Redirect, Link, Switch } from "react-router-dom";

原因:

BrowserRouter是需要对服务器端进行配置的,因为不同的path默认会请求不同的服务器资源,HashRouter的话都是请求的index.html这个资源,所以不会有问题。npm run dev不会有问题,是因为你的node起的本地服务已经做好了这个转发配置

2、Safari不能正确解析yyyy-mm-dd

var date_format = "2016-06-10".split('-').join('/')
var deadline = new Date(date_format + " 23:59");

3、JS判断分秒为零时

let date_format = date && date.split('-').join('/')
const time = new Date(date_format);
const hour = time.getHours()
const min = time.getMinutes()
if (hour === 0 && min === 0) return true;
else return false;

4、JS比当前时间多一个小时

let now = new Date();
const nowAfterHours = new Date(now.getTime() + 60 * 60 * 1000);

5、JS时间分钟小于30调整为30,大于30小于60调整为60

let startTime = new Date(startdate);
let endTime = new Date(endTime);
if (endTime.getMinutes() < 30 && endTime.getMinutes() > 0) {
     endTime = new Date(endTime.getTime() + (30 - endTime.getMinutes()) * 60 * 1000);
} else if (endTime.getMinutes() > 30) {
    endTime = new Date(endTime.getTime() + (60 - endTime.getMinutes()) * 60 * 1000);
}

6、JS判断对象类型

typeof form.endate === "object"

7、字符串匹配关键字全部替换
如下替换href="//为href="http://

str.replace(new RegExp( "href=\"//" , "g" ), "href=\"http://")

8、前端根据手机设备调用原生方法

const browser = {
    versions: (function () {
        const u = navigator.userAgent,
            app = navigator.appVersion;

        return {
            ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), // ios终端
            android: u.indexOf("Android") > -1 || u.indexOf("Linux") > -1, // android终端或者uc浏览器
            iPhone: u.indexOf("iPhone") > -1 || u.indexOf("Mac") > -1, // 是否为iPhone或者QQHD浏览器
            iPad: u.indexOf("iPad") > -1, // 是否iPad
            weChat: u.indexOf("MicroMessenger") > -1
        };
    })()
};
// 扫一扫
export function scan() {
    if (browser.versions.android) {
        window['WebViewJavascriptBridge'].callHandler("scan");
    } else if (browser.versions.ios || browser.versions.iPhone || browser.versions.iPad) {
        window['webkit'].messageHandlers.scan.postMessage("");
    }
}

9、iOS及safari时间解析错误

function toDate(time:string,fmt?: string) {
    if (fmt == null) fmt = 'yyyy-MM-dd hh:mm:ss';

    const str = time.replace(/\T/g, ' ');
    // fmt为日期格式,str为日期字符串
    const reg = /([yMdhmsS]+)/g; // 日期格式中的字符
    let key = {}, conv = (v) => { let val = parseInt(v, 10); return isNaN(val) ? 0 : val; };
    const tmpkeys = fmt.match(reg);
    for (let i = 0; i < tmpkeys.length; i++) {
        key[tmpkeys[i].substr(0, 1)] = i + 1;
    }
    const r = str.match(fmt.replace(reg, "(\\d+)"));
    return new Date(conv(r[key["y"]]), conv(r[key["M"]]) - 1, conv(r[key["d"]]), conv(r[key["h"]]), conv(r[key["m"]]), conv(r[key["s"]]));
}

或者

export function getDate(date: string | Date, def?: Date): Date | undefined {
    return date instanceof Date
        ? date
        : date
        ? new Date(
              date
                  .replace(/\-/g, "/")
                  .replace(/T/g, " ")
                  .substr(0, 19)
          )
        : def;
}

10、获取两天后的时间或者N月后时间

/**
 * 获取指定日期N天后日期
 * @param days GetDateStr
 */
export function getSetDateStr(date: string, days: number, fmt: string = "yyyy-MM-dd") {
    let dd = new Date(date);
    dd.setDate(dd.getDate() + days); // 获取n天后的日期
    return formatDate(dd, fmt)
}
/**
 * 获取指定日期N月后日期
 * @param days GetDateStr
 */
let date = new Date();
date.setMonth(date.getMonth() + N)

11、js取消键盘响应

 $('.autoFocus').blur();

12、日历插件
插件地址

13、iconfont下载全部

在浏览器中按f12打开【开发人员工具】,找到【console(控制台)】,输入以下代码,再按回车,稍等片刻即可把全部图标加入购物车
var ll = document.getElementsByClassName('icon-gouwuche1'); for (var i=0; i<ll.length;i++){ ll[i].click(); }

14、react路由跳转传参

this.goTo({
       pathname: `orderDetail`,
       state: this.roomData
})
//接收参数
this.props.location.state

goTo(path: string | LocationDescriptorObject, state?: any) {
        if (this.props.match && path) {
            let isString = typeof path === "string",
                paths = isString ? (path as string) : (path as LocationDescriptorObject).pathname;

            if (!PREFIX_REG.test(paths)) {
                const url = this.props.match.url;

                paths = `${url}${SUFFIX_REG.test(url) ? "" : "/"}${paths}`;

                isString ? (path = paths) : ((path as LocationDescriptorObject).pathname = paths);
            }
        }

        this.__goTo(path, state);
}

protected __goTo(path: string | LocationDescriptorObject, state?: any) {
        this.props.history && this.props.history.push(path as any, state);
}

15、js根据数组循环key值获取class类型,确保相邻值不同

randomClassValue(i) {
        let value = i % 4 ? i % 4 : 4
        return "back-" + value;
}

16、超出部分可以滚动

<div style={{maxHeight: "100%", overflowY: "scroll"}}>
        <WhiteSpace/>
        {this.renderLoading(this.props.state.showloading)}
        {this.renderFormData()}
</div>

17、获取本周开始结束时间及本周是第几周

this.BeginDate = getWeekDate("start");
this.EndDate = getWeekDate("end");
/** 获取本周开始结束时间 */
export function getWeekDate(data: any) {
    const now = new Date(); // 当前日期
    let nowDayOfWeek = now.getDay(); // 今天本周的第几天
    if (nowDayOfWeek === 0) nowDayOfWeek = 7;
    const nowDay = now.getDate(); // 当前日
    const nowMonth = now.getMonth(); // 当前月
    const nowYear = now.getFullYear(); // 当前年
    if (data === "start") return new Date(nowYear, nowMonth, nowDay - nowDayOfWeek + 1).format("yyyy-MM-dd");
    else return new Date(nowYear, nowMonth, nowDay + (7 - nowDayOfWeek)).format("yyyy-MM-dd");
}
/** 获取本周是第几周 */
  getWeek(dt) {
    let d1 = new Date(dt);
    let d2 = new Date(dt);
    d2.setMonth(0);
    d2.setDate(1);
    let rq = d1 - d2;
    let days = Math.ceil(rq / (24 * 60 * 60 * 1000));
    let num = Math.ceil(days / 7);
    console.log("num", num);
    return num;
  }

18、获取下一周或者获取上一周

addWeek(week: number) {
        this.BeginDate = getDate(this.BeginDate).dateAdd("w", week).format("yyyy-MM-dd");
        this.EndDate = getDate(this.EndDate).dateAdd("w", week).format("yyyy-MM-dd");
        const {tabIndex} = this.state as any;
        this.getData(null, tabIndex);
    }
// 第几周
getDate(date: string | Date): Date {
    return date instanceof Date
        ? date
        : date &&
        new Date(
            date
                .replace(/\-/g, "/")
                .replace(/T/g, " ")
                .substr(0, 19)
        );
}

19、react前端升级样式版本过高报错

const style = { style: { width: '100%', minWidth: '75px' } } as any;
<List.Item
                        className="menuadd"
                        wrap
                        extra={
                            <Stepper
                                {...style}
                                showNumber
                                min={1}
                                value={val}
                                onChange={this.onChange}
                            />}
                    ></List.Item>

20、数组遍历改变值,蚂蚁组件pick组件赋值

entrances = this.state.v5sflc ? this.state.v5sflc.map(c => ({ label: c.TagName, value: c })) : [];

21、react路由跳转重写

componentDidMount() {
        window['payGoTo'] = (path, state) => {
            this.path = state ? path : null;
            this.goTo(path);
        }
        this.props.getOrderDetailAction(this.props.match.params.id);
}
protected __goTo(path: string | LocationDescriptorObject, state?: any) {
        if (this.props.match.params.type === "submit") {
            this.props.history && this.props.history.push(path as any, state);
        } else if (this.path) {
            // alert(`${this.props.match.url}/${this.path}`)
            let index = `${this.props.match.url}}`.indexOf("resourcePayErr");
            let result = `${this.props.match.url}}`.substr(0, index);
            // alert(result)
            this.props.history && this.props.history.replace(`${result}${this.path}` as any, state);
            this.path = null;
        }
}

22、html获取base64串并与iOS交互

<!DOCTYPE html>
<html lang="en">
<head>
    <meta name="viewport"content="width=device-width, initial-scale=1, maximum-scale=1.0,user-scalable=no;" />
    <title>html5实现上传</title>
    <script type="text/javascript" src="configure.js"></script>
</head>
<body>
    <img id="showImg" height="200" width="200" />
    <input type="file" onchange="changeFile(event);" />
    <script type="text/javascript">
        function changeFile(event) {
            file = event.target.files[0];
            var a = new FileReader();
            a.onload = function (e) {
                var base64Str = e.target.result;//获取base64
                console.log('base64Str', base64Str);
                //下面是测试得到的base64串能否正常使用:
                // document.getElementById('showImg').src = base64Str;
                window['webkit'].messageHandlers.changePic.postMessage(base64Str);
            }
            a.readAsDataURL(file);
        }
        function picResult(result){
            document.getElementById('showImg').src = result;
        }
    </script>
</body>
</html>

23、html生成iOS启动图方法
Contents.json

{
  "images" : [
    {
      "extent" : "full-screen",
      "idiom" : "iphone",
      "subtype" : "2436h",
      "filename" : "LoadingX@3x.png",
      "minimum-system-version" : "11.0",
      "orientation" : "portrait",
      "scale" : "3x"
    },
    {
      "orientation" : "landscape",
      "idiom" : "iphone",
      "extent" : "full-screen",
      "minimum-system-version" : "11.0",
      "subtype" : "2436h",
      "scale" : "3x"
    },
    {
      "extent" : "full-screen",
      "idiom" : "iphone",
      "subtype" : "736h",
      "filename" : "Loading@3x.png",
      "minimum-system-version" : "8.0",
      "orientation" : "portrait",
      "scale" : "3x"
    },
    {
      "orientation" : "landscape",
      "idiom" : "iphone",
      "extent" : "full-screen",
      "minimum-system-version" : "8.0",
      "subtype" : "736h",
      "scale" : "3x"
    },
    {
      "extent" : "full-screen",
      "idiom" : "iphone",
      "subtype" : "667h",
      "filename" : "Loading@2x.png",
      "minimum-system-version" : "8.0",
      "orientation" : "portrait",
      "scale" : "2x"
    },
    {
      "orientation" : "portrait",
      "idiom" : "iphone",
      "filename" : "Default@2x.png",
      "extent" : "full-screen",
      "minimum-system-version" : "7.0",
      "scale" : "2x"
    },
    {
      "extent" : "full-screen",
      "idiom" : "iphone",
      "subtype" : "retina4",
      "filename" : "Default-568h@2x.png",
      "minimum-system-version" : "7.0",
      "orientation" : "portrait",
      "scale" : "2x"
    },
    {
      "orientation" : "portrait",
      "idiom" : "iphone",
      "extent" : "full-screen",
      "scale" : "1x"
    },
    {
      "orientation" : "portrait",
      "idiom" : "iphone",
      "filename" : "Default@2x-1.png",
      "extent" : "full-screen",
      "scale" : "2x"
    },
    {
      "orientation" : "portrait",
      "idiom" : "iphone",
      "filename" : "Default-568h@2x-1.png",
      "extent" : "full-screen",
      "subtype" : "retina4",
      "scale" : "2x"
    }
  ],
  "info" : {
    "version" : 1,
    "author" : "xcode"
  }
}

生成启动图html代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0,user-scalable=no;"/>
    <title>html5生成iOS启动图</title>
    <style type="text/css">
        .main{
             text-align: center; /*让div内部文字居中*/
             background-color: #fff;
             border-radius: 20px;
             width: 300px;
             height: 350px;
             margin: auto;
             position: absolute;
             top: 0;
             left: 0;
             right: 0;
             bottom: 0;
        }

         .up-file {
             padding: 4px 10px;
             height: 40px;
             width: 240px;
             text-align: center;
             line-height: 40px;
             position: relative;
             cursor: pointer;
             background: #44bbff;
             color: #FFFFFF;
             border: 1px solid #ddd;
             border-radius: 4px;
             overflow: hidden;
             display: inline;
             zoom: 1;
        }
        .up-file input {
             position: absolute;
             font-size: 100px;
             right: 0;
             top: 0;
             opacity: 0;
             cursor: pointer;
        }
        .remark {
        	 width: 300px;
        	 font-size: 12px;
        	 color: red;
        	 text-align: left;
        	 margin-left: 15px;
        }
        .divmargin-top {
        	margin-top: 20px;
        }
    </style>
</head>
<body>
<div class="main">
	<canvas id="canvas" style="border:1px solid #c3c3c3;display:none;"></canvas>
    <a class="up-file">
       <input type="file" onchange="changeFile(event);" />选取图片生成指定尺寸图片
    </a>
    <div class="divmargin-top">
 	   <div class="remark">1、在picConfigure中配置图片名称和对应图片尺寸</div>
       <div class="remark">2、选取图片后会自动生成并下载图片</div>
    </div>
</div>
<script type="text/javascript">
	function changeFile(event) {
		file = event.target.files[0];
		var a = new FileReader();
		a.onload = function (e) {
			var base64Str = e.target.result;//获取base64
			var image = new Image();
			image.src = base64Str;
			var picConfigure = [
				{name: "Default-568h@2x-1.png", width: 640, height: 1136},
				{name: "Default-568h@2x.png", width: 640, height: 1136},
				{name: "Default@2x-1.png", width: 640, height: 960},
				{name: "Default@2x.png", width: 640, height: 960},
				{name: "Loading@2x.png", width: 750, height: 1334},
				{name: "Loading@3x.png", width: 1242, height: 2208},
				{name: "LoadingX@3x.png", width: 1125, height: 2436},]
			setTimeout(function () {
				for (var i = 0; i < picConfigure.length; i++) {
					var canvas = document.getElementById("canvas");
					var context = canvas.getContext("2d");
					var width=picConfigure[i].width, height=picConfigure[i].height;
					canvas.setAttribute("width", width + "px");
					canvas.setAttribute("height", height + "px");
					context.drawImage(image,0,0,width,height);
					downLoadCanvasImage(canvas, picConfigure[i].name)
				}
			},500)

		}
		a.readAsDataURL(file);
	}

	function downLoadCanvasImage(canvas, name) {
		var a = document.createElement("a");
		a.href = canvas.toDataURL();
		a.download = name || '下载图片名称';
		a.click();
	}
</script>
</body>
</html>

改进版本

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0,user-scalable=no;"/>
        <title>html5生成iOS启动图</title>
        <style type="text/css">
            .main{
                text-align: center; /*让div内部文字居中*/
                background-color: #fff;
                border-radius: 20px;
                width: 300px;
                height: 350px;
                margin: auto;
                position: absolute;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
            }
        
        .up-file {
            padding: 4px 10px;
            height: 40px;
            width: 240px;
            text-align: center;
            line-height: 40px;
            position: relative;
            cursor: pointer;
            background: #44bbff;
            color: #FFFFFF;
            border: 1px solid #ddd;
            border-radius: 4px;
            overflow: hidden;
            display: inline;
            zoom: 1;
        }
        .up-file input {
            position: absolute;
            font-size: 100px;
            right: 0;
            top: 0;
            opacity: 0;
            cursor: pointer;
        }
        .remark {
            width: 300px;
            font-size: 12px;
            color: red;
            text-align: left;
            margin-left: 15px;
        }
        .divmargin-top {
            margin-top: 20px;
        }
        </style>
    </head>
    <body>
        <div class="main">
            <canvas id="canvas" style="border:1px solid #c3c3c3;display:none;"></canvas>
            <a class="up-file">
                <input type="file" onchange="changeFile(event);" />选取图片生成指定尺寸图片
            </a>
            <div class="divmargin-top">
                <div class="remark">1、在picConfigure中配置图片名称和对应图片尺寸</div>
                <div class="remark">2、选取图片后会自动生成并下载图片</div>
            </div>
        </div>
        <script type="text/javascript">
            function changeFile(event) {
                file = event.target.files[0];
                var a = new FileReader();
                a.onload = function (e) {
                    var base64Str = e.target.result;//获取base64
                    var image = new Image();
                    image.src = base64Str;
                    var picConfigure = [
                                        {name: "Default-568h@2x-1.png", width: 640, height: 1136},
                                        {name: "Default-568h@2x.png", width: 640, height: 1136},
                                        {name: "Default@2x-1.png", width: 640, height: 960},
                                        {name: "Default@2x.png", width: 640, height: 960},
                                        {name: "Loading@2x.png", width: 750, height: 1334},
                                        {name: "Loading@3x.png", width: 1242, height: 2208},
                                        {name: "LoadingX@3x.png", width: 1125, height: 2436},]
                                        setTimeout(function () {
                                                   for (var i = 0; i < picConfigure.length; i++) {
                                                   var canvas = document.getElementById("canvas");
                                                   var context = canvas.getContext("2d");
                                                   var width=picConfigure[i].width, height=picConfigure[i].height;
                                                   canvas.setAttribute("width", width + "px");
                                                   canvas.setAttribute("height", height + "px");
                                                   context.drawImage(image,0,0,width,height);
                                                   downLoadCanvasImage(canvas, picConfigure[i].name)
                                                   }
                                                   },500)
                                                   
                }
                a.readAsDataURL(file);
            }
        
        function dataURLtoBlob(dataurl) {
            var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
            while(n--){
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new Blob([u8arr], {type:mime});
        }
        function downLoadCanvasImage(canvas, name) {
            var a = document.createElement("a");
            var imgData = canvas.toDataURL();
            var strDataURI = imgData.substr(22, imgData.length);
            var blob = this.dataURLtoBlob(imgData);
            var objurl = URL.createObjectURL(blob);
            a.href = objurl;
            
            console.log("1111", a.href)
            a.download = name || '下载图片名称';
            a.click();
        }
        </script>
    </body>
</html>


24、公司问题记录:
(1)报错Error: Cannot find module ‘uglifyjs-webpack-plugin’

sudo cnpm i -S uglifyjs-webpack-plugin
// pure_getters: true,

(2)内部安装

npm config set registry http://192.168.1.247:86/npm/RECO.NPM/
cnpm config set registry http://192.168.1.247:86/npm/RECO.NPM/
yarn config set registry http://192.168.1.247:86/npm/RECO.NPM/

(3)报错

ERROR in [at-loader] ./node_modules/@types/react-transition-group/TransitionGroup.d.ts:16:45 
    TS2314: Generic type 'ReactElement<P>' requires 1 type argument(s).
ERROR in [at-loader] ./node_modules/@types/react-dom/index.d.ts:90:18 
    TS2314: Generic type 'ReactElement<P>' requires 1 type argument(s).

版本匹配不上造成,对应位置加上标签

type TransitionGroupProps<T extends keyof JSX.IntrinsicElements = "div", V extends ReactType = any> =
        (IntrinsicTransitionGroupProps<T> & JSX.IntrinsicElements[T]) | (ComponentTransitionGroupProps<V>) & {
        children?: ReactElement<TransitionProps> | Array<ReactElement<TransitionProps>>;
        childFactory?<P>(child: ReactElement<P>): ReactElement<P>;
        [prop: string]: any;
    };
<P>(
        element: ReactElement<P>,
        container: Element | null,
        callback?: () => void
    ): Component<P, ComponentState> | Element | void;

25、截取字符串中中文开头的字符
截取字符串如下

<p><span style="color:#a5a5a5">城国际都市综合体位于位于地铁10号线紫藤路站上盖,紧邻吴中路和外环高架内侧,由24万平方米万象城顶级购物中心,14万平方米超甲级写字楼集群,3万平方米国际精品酒店组成,总体量达53万平方米,<span style="font-size:16px">是截止目前区最大的最高端的商业综合体项目</span><span style="font-size:16px">。</span><br/>上象城国际都市综合体延续和超越了万象城产品线的卓越品质,在每个业态上都有所创新和突破。</span></p><p><span style="color:#a5a5a5">上海国际都市综合体位于上海“西大门”虹桥区域,处于虹桥涉外贸易中心、虹桥临空经济园区、七宝生态商务区、南方商城商务区、漕河泾商务区的中间位置,尽占大虹桥CBD核心区位优势。距虹桥综合交通枢纽仅2千米,一小时辐射繁荣的长三角经济圈。</span></p><p><span style="color:#a5a5a5">上海购物中心总体量24万平方米,上海象城购物中心是集合全球顶级奢侈品牌、都会时尚品牌、丰富的寰宇美食、超大型IMAX影院,奥林匹克标准真冰场、五星级KTV、家用家居、儿童亲子、高端超市及地铁博物馆为一体的一站式<span style="color: rgb(165, 165, 165);"></span>体验式顶级购物中心。<br/>14万平米共11栋上象城都市超甲级写字楼集群,由5栋总部甲级写字楼、6栋超甲级写字楼构成,恢宏巨制,自成一体,构建全新商业生态的城市CBD核心,尽显国际顶级写字楼高端商务气质。<br/>3万平米精品酒店,容纳国际知名酒店品牌以及顶尖软硬件标准配置,领衔3万平米会务、商旅及休闲高端服务的精品之选,商务出行和休闲旅游的绝佳选择。<br/>5万平米生态空中花园,力邀国际顶级景观设计师倾力打造,沪上首个空中花园生态景观办公,提供无限界的开放商务休闲空间体验。<br/>别具一格的业态组合及先进设计理念都将使得上城成为万象城产品线中的一颗璀璨明珠。</span></p><p></p>



matchReg(str) {
    let tempstr = str.match(/[\u4e00-\u9fa5]/g);
    let resultstr = str.substring(str.indexOf(tempstr[0]), 50);
    return resultstr;
}


26、new Date获取及设置时间

let dd = new Date();
//dd.setHours(23);
// dd.setMinutes(39)
// dd.setSeconds(0)
// console.log("getCurrentUser11", dd)
dd.setDate(dd.getDate() + 14); // 获取两周后的日期

27、iOS中Fiexd不起作用

#editorContainer .zxeditor-container .zxeditor-toolbar-wrapper{
    position: sticky;
    position: fixed;
    transform: translateZ(0);
}

28、字符串换行

\r\n

29、html中空格占位符

&nbsp;

30、蚂蚁组件TextareaItem提交的内容包含换行,如何展示

 <List.Item>
          <Flex>
               <span className='margin-right-sm grayColor2'>备注留言</span>
              <Flex.Item className='no-omit'><HtmlContent className="park-details resource-color" html={order.Description.replace(/\n/g, "<br>")}/></Flex.Item>
         </Flex>
</List.Item>

31、获取本月开始日期和结束日期

const now = new Date(); // 当前日期
const nowMonth = now.getMonth(); // 当前月
const nowYear = now.getFullYear(); // 当前年
let start = new Date(nowYear, nowMonth, 1).format("yyyy-MM-dd");
let end = new Date(nowYear, nowMonth, 30).format("yyyy-MM-dd");

32、加载html格式字符串并显示出效果

<div dangerouslySetInnerHTML={{ __html: itm.Remarks }} />

33、js数值计算保留两位小数

1)ceil():将小数部分一律向整数部分进位。Math.ceil(12.2)返回13.0
2)floor():舍去小数,仅保留整数。Math.floor(12.2)返回12.0
3)round():进行四舍五入。Math.round(12.2)返回12.0,Math.round(12.5)返回13.0。

Math.ceil(number * 100) / 100         保留两位小数第三位小数进位
Math.floor(number * 100) / 100       保留两位小数不四舍五入
Math.round(number * 100) / 100 或者 parseFloat(a.toFixed(2))        保留两位小数并四舍五入

34、h5微信JS-SDK内分享
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115

export function wxShare(title: any, img?: any, desc?: any) {
    const url = location.href.split("#")[0];
    shhzwechatService.getWxConfig(url).success(d => {
        wx.config(Object.assign({ jsApiList: ["checkJsApi", "onMenuShareTimeline", "onMenuShareAppMessage", "onMenuShareQQ", "onMenuShareWeibo"] }, d));

        wx.ready(function() {
            wx.onMenuShareAppMessage({
                title: title, // 分享标题
                imgUrl: img || "http://xx/logo.jpg", // 分享图标
                desc: desc || "" // 分享图标
            });

            wx.onMenuShareTimeline({
                title: title,
                desc: desc || "",
                imgUrl: img || "http://xx/logo.jpg" // 自定义图标
            });
        });
    });
}

35、 前端antd-mobiel中<List renderHeader={() => “申请人信息”} className=“my-list”>类型报错解决方案
FDFFB366991518797B3B0EA61244BD27.png

36、bitech时间判断

import {checkCh} from "./letterlist";
export function getDate(date: string | Date, def?: Date): Date | undefined {
    return date instanceof Date
        ? date
        : date
        ? new Date(
              date
                  .replace(/\-/g, "/")
                  .replace(/T/g, " ")
                  .substr(0, 19)
          )
        : def;
}

export function formatNow(fmt: string = "yyyy-MM-dd") {
    return formatDate(new Date(), fmt);
}

export function formatDateTime(date: Date | string, fmt: string = "yyyy-MM-dd hh:mm:ss") {
    return formatDate(date, fmt);
}

export function formatDate(date: Date | string, fmt: string = "yyyy-MM-dd") {
    if (date instanceof Date) return date.format(fmt);
    else if (date) {
        try {
            return getDate(date)!.format(fmt);
            // tslint:disable-next-line:no-empty
        } catch {}
    }
    return date;
}
/**
 * 获取当前日期N天后日期
 * @param days GetDateStr
 */
export function getDateStr(days?: any, fmt: string = "yyyy-MM-dd") {
    let dd = new Date();
    dd.setDate(dd.getDate() + days); // 获取n天后的日期
    return formatDate(dd, fmt)
}

/**
 * 获取指定日期N天后日期
 * @param days GetDateStr
 */
export function getSetDateStr(date: string, days: number, fmt: string = "yyyy-MM-dd") {
    let dd = new Date(date);
    dd.setDate(dd.getDate() + days); // 获取n天后的日期
    return formatDate(dd, fmt)
}

export function formatFormalDate(date: Date | string, fmt: string = "yyyy-MM-dd hh:mm:ss") {
    if (date instanceof Date) return date.format(fmt);
    else if (date) {
        try {
            return getDate(date)!
                .format(fmt)
                .split(".")[0];
            // tslint:disable-next-line:no-empty
        } catch {}
    }

    return date;
}

export function formatDates(fmt: string = "yyyy-MM-dd") {
    return (date: Date) => formatDate(date, fmt);
}

export function formatDateYtom(date: string) {
    let fmt = "yyyy-MM-dd hh:mm";
    return this.formatDate(date, fmt);
}

export function parseStandard(time: string, format: string = "yyyy-MM-dd hh:mm:ss") {
    let t = new Date(time);
    let tf = function(i) {
        return (i < 10 ? "0" : "") + i;
    };
    return format.replace(/yyyy|MM|dd|hh|mm|ss/g, a => {
        switch (a) {
            case "yyyy":
                return tf(t.getFullYear());

            case "MM":
                return tf(t.getMonth() + 1);

            case "mm":
                return tf(t.getMinutes());

            case "dd":
                return tf(t.getDate());

            case "hh":
                return tf(t.getHours());

            case "ss":
                return tf(t.getSeconds());
            default:
                return "";
        }
    });
}

export function format(this: Date, fmt: string): string {
    const o = {
        "M+": this.getMonth() + 1, // 月份
        "d+": this.getDate(), // 日
        "h+": this.getHours(), // 小时
        "m+": this.getMinutes(), // 分
        "s+": this.getSeconds(), // 秒
        "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
        S: this.getMilliseconds() // 毫秒
    };

    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));

    for (const k in o) if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));

    return fmt;
}

(Date as any).prototype.format = format;

export function formatTime(date: Date | string, fmt: string = "hh:mm") {
    if (date instanceof Date) return date.format(fmt);
    else if (date) {
        try {
            return getDate(date)!.format(fmt);
            // tslint:disable-next-line:no-empty
        } catch {}
    }

    return date;
}


/**
 * 判断周几
 */
export function getWeekStr(date: string, days: number) {
    let dd = new Date(date);
    dd.setDate(dd.getDate() + days); // 获取n天后的日期
    let week = dd.getDay();
    let str;
    if (week === 0) {
        str = "周日";
    } else if (week === 1) {
        str = "周一";
    } else if (week === 2) {
        str = "周二";
    } else if (week === 3) {
        str = "周三";
    } else if (week === 4) {
        str = "周四";
    } else if (week === 5) {
        str = "周五";
    } else if (week === 6) {
        str = "周六";
    }
    return str;
}
export function getAvatar(name: string, avatar?: string) {
    if (avatar) {

        return avatar.toUpperCase();
    } else {
        let letter = getChineseHeadLetter(name);
        return letter ? letter.length === 1 ? letter.toUpperCase() : letter.toUpperCase().slice(0, 1) : "";
    }
}
// 参数,中文字符串
// 返回值:拼音首字母串数组
export function getChineseHeadLetter(str) {
    if (typeof (str) !== "string")
        return;
    let arrResult = new Array(); // 保存中间结果的数组

    // 获得unicode码
    let ch = str.charAt(0);
    // 检查该unicode码是否在处理范围之内,在则返回该码对映汉字的拼音首字母,不在则调用其它函数处理
    let s = checkCh(ch);

    // 处理arrResult,返回所有可能的拼音首字母串数组
    return s.toLowerCase();
}

// function checkCh(ch) {
//     let uni = ch.charCodeAt(0);

//     // 如果不在汉字处理范围之内,返回原字符,也可以调用自己的处理函数
//     if (uni > 40869 || uni < 19968)
//         return ch;
//     // 检查是否是多音字,是按多音字处理,不是就直接在strChineseFirstPY字符串中找对应的首字母
//     return (oMultiDiff[uni] ? oMultiDiff[uni] : (strChineseFirstPY.charAt(uni - 19968)));
// }





37、input输入一个字符自动切换下一个输入框

<input className="input1" onChange={(e) => this.moveNext.bind(this, e, 1)()}/>
<input className="input2" onChange={(e) => this.moveNext.bind(this, e, 2)()}/>
<input className="input3" onChange={(e) => this.moveNext.bind(this, e, 3)()}/>
<input className="input4" onChange={(e) => this.moveNext.bind(this, e, 4)()}/>
<input className="input5" onChange={(e) => this.moveNext.bind(this, e, 5)()}/>
<input className="input6" onChange={(e) => this.moveNext.bind(this, e, 6)()}/>
<input className="input7" onChange={(e) => this.moveNext.bind(this, e, 7)()}/>
    moveNext(object, index) {
        if (object.target.value.length === 1) {
            $(`.input${index + 1}`).focus();
        }
    }
    

38、获取两时间间隔多少天,天数查询

export  function timeInterval(starttime, endtime?) {
    let startTime = getDate(starttime); // 开始时间
    let endTime = getDate(endtime ? endtime : new Date()); // 结束时间
    let usedTime = endTime.getTime() - startTime.getTime(); // 相差的毫秒数
    let days = Math.floor(usedTime / (24 * 3600 * 1000)); // 计算出天数
    let leavel = usedTime % (24 * 3600 * 1000); // 计算天数后剩余的时间
    let hours = Math.floor(leavel / (3600 * 1000)); // 计算剩余的小时数
    let leavel2 = leavel % (3600 * 1000); // 计算剩余小时后剩余的毫秒数
    let minutes = Math.floor(leavel2 / (60 * 1000)); // 计算剩余的分钟数
    return days + '天' + hours + '时' + minutes + '分';
}

39、微信接通银联支付

<!DOCTYPE html>
<html lang="zh">
<head>
    <title id="title">BITECH IPARK SAAS</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="renderer" content="webkit|ie-stand">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta http-equiv="Content-Language" content="zh-cn" />
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
</head>
<body>
    <a onclick="createPay()">模拟支付</a>
    <p id="jsonurl"></p>
    <script type="text/javascript">
        const appid = 'wx3545eb792d885a20';

        function get(url, params) {
            let uri = new URL(url, location.href);
            if (params) {
                for (var key in params)
                    uri.searchParams.set(key, params[key]);
            }

            return fetch(uri, {
                method: 'GET',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                }
            }).then(response => response.json());
        }

        function post(url, data) {
            let uri = new URL(url, location.href);

            return fetch(uri, {
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            }).then(response => response.json());
        }



        function createPay() {
            let order = {
                BindTableName: 'TEST',
                BindTableID: 1,
                Subject: '测试订单',
                TotalAmount: 1,
                ReturnUrl:'http://localhost:12225/WeChat.html'
            };
            post('ChianUMSPay/Index/WechatPay', order).then(json => {
                console.log(json)
                location.href = json;
                //WeixinJSBridge.invoke(
                //    'getBrandWCPayRequest',
                //    json,
                //    result => {
                //        alert(JSON.stringify(result));
                //        if (result.err_msg === "get_brand_wcpay_request:ok") {
                //            alert('支付成功');
                //        }
                //    }
                //);
            });
        }

        //if (typeof WeixinJSBridge == "undefined") {
        //    if (document.addEventListener) {
        //        document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
        //    } else if (document.attachEvent) {
        //        document.attachEvent('WeixinJSBridgeReady', getOpenID);
        //        document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
        //    }
        //} else {
        //    onBridgeReady();
        //}
    </script>
</body>
</html>

40、获取url参数

    getQueryString(name) {
        let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        let r = this.props.location.search.substr(1).match(reg);
        if (r != null) return r[2];
        return null;
    }

41、车牌号查询类似的输入框
屏幕快照 2019-05-22 上午8.58.52.png

<input className="input2"  onChange={e => this.moveNext.bind(this, e, 2)()} onKeyDown={e => this.cancelLast.bind(this, e, 2)()} />
   cancelLast(object, index) {
        if (object.keyCode === 8 && (object.target.value.length === 1 || object.target.value.length === 0)) {
            setTimeout(() => {
                $(`.input${index}`).val("");
                $(`.input${index - 1}`).focus();
            }, 30)
        }
    }

    moveNext(object, index) {
        if (object.target.value.length === 1) {
            $(`.input${index + 1}`).focus();
        }
        if (object.target.value.length > 1) {
            let inputValue = $(`.input${index}`).val();
            let inputValues = `${inputValue}`
            $(`.input${index}`).val(inputValues.substring(1, 2))
            $(`.input${index + 1}`).focus();
        }
        if (object.target.value.length === 0) {
            $(`.input${index - 1}`).focus();
        }

    }
    for (let i = 0; i < 8; i++) {
        if (i === 0 && $(`.input${i + 1}`).html()) {
                carNum = carNum + $(`.input${i + 1}`).html();
         } else if ($(`.input${i + 1}`).val()) {
                carNum = carNum + $(`.input${i + 1}`).val();
         }
    }

42、js立即执行防抖函数,防止方法调用重复

debounce(func, wait) {
        let timeout;
        return function () {
            let context = this;
            let args = arguments;
            if (timeout) clearTimeout(timeout);
            let callNow = !timeout;
            timeout = setTimeout(() => {
                timeout = null;
            }, wait)
            if (callNow) func.apply(context, args);
        }
    }

实例

let debounceFunLike = this.debounce(this.likeActivity.bind(this), 5000);
debounceFunLike()
debounceFunLike()
debounceFunLike()

43、jquery处理字符串解析dom元素

let $html = $(html);
    $html.find("img").each((index, img) => {
      let $img = $(img);
      let imgSrc = $img.attr("src");
      if (imgSrc && imgSrc.startsWith("./"))
      $img.attr("src", "http://test.bitech.cn/reco8.park/" + imgSrc.substr(1));
    });
    $html.find("a").each((index, a) => {
      let $a = $(a);
      let aHref = $a.attr("href");
      if (aHref && aHref.startsWith("./"))
        $a.attr("href", "http://test.bitech.cn/reco8.park/" + aHref.substr(1));
    });

44、hybrid实现录音及播放

*startRecord({ fail, data, successCall }, { call, put }) {
        // 项目详情语音录入开始
        try {
            try {
                yield put({ type: "showLoading" });
                const result = yield call(startRecord.bind(this, data));
                let formDate = createVoiceData(result, data);
                yield call(quickAddTrackService.discernVoiceAddTrack, formDate);
                // alert(result.get("SourceVideo").name)
                // alert(result.get("SourceVideo").size)
                successCall();
            } catch (error) {
                fail!(error.errmsg);
            } finally {
                yield put({ type: "hideLoading" });
            }
        } catch (error) {
            fail!(error.errmsg);
        }
    }
// 获取音频录音
export function startRecord() {
    let result: Promise<any> | null = null;
    // // 模拟获取音频录音
    // // 有数据测试
    // let file = dataURLtoFile(audioData, "测试");
    // result = Promise.resolve(file);
    // return result;
    // 正式获取音频录音
    result = postBridgeMessage("startRecord");
    if (result) {
        return result.then(({ data, name }) => {
            // alert(`11111${data}${name}`)
            let file = dataURLtoFile(data, name);
            return file;
            // return createData(file, postdata);
        });
    }
}
export function dataURLtoFile(dataurl: string, filename: string) {
    const arr = dataurl.split(","),
        mime = arr![0]!.match(/:(.*?);/)![1],
        bstr = atob(arr[1]);

    let n = bstr.length;
    const u8arr = new Uint8Array(n);

    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    let date = new Date();
    return new File([u8arr], `${filename}${date.format("yyyyMMddhhmmss")}.wav`, { type: mime });
}
export function createVoiceData(file: any, postdata: any) {
    const formData = new FormData();
    let date = new Date();
    let fileName = `SourceVideo${date.format("yyyyMMddhhmmss")}` + (/^.*?(\.\w+)$/.exec(file!.name)![1] || "");
    if (postdata.ParentID) {
        formData.append("ClueID", postdata.ClueID);
        formData.append("Layer", postdata.Layer);
        formData.append("ParentID", postdata.ParentID);
        formData.append("ChildParentID", postdata.ChildParentID);
        formData.append("ToInputer", postdata.ToInputer);
        formData.append("video", file, fileName);
        formData.append("SourceVideo", file, fileName);
    } else {
        formData.append("ClueID", postdata.ClueID);
        formData.append("video", file, fileName);
        formData.append("SourceVideo", file, fileName);
    }
    return formData;
}

播放录音

<audio id="speekplayer" src=""></audio>
 document.getElementById("speekplayer").src = transformUrl(item.Attach.FilePath);
                                                        document.getElementById("speekplayer").play();

45 、web端微信及支付宝支付

*apppay({ error, paytype, payway, order, resourceType, weakthis, callback }, { call, put }) {
        try {
            console.log(
                "支付啊",
                `${window.location.protocol + "//" + window.location.host}/#/resource/roommeet/${
                    Number(resourceType) === ResourceType.MEETING ? "roommeet" : "roomarea"
                }/submitSuccess/${order.ID}`
            );
            const files = new FormData();
            files.append("BindTableName", "BIResourceOrder");
            files.append("Subject", order.ResourceName);
            files.append("TotalAmount", "0.01");
            files.append("BindTableID", `${order.ID}`);
            files.append("TradeChannel", paytype);
            files.append("ParkID", localStorage.ParkID);
            files.append("PaymentType", "NATIVE");
            files.append(
                "ReutrnUrl",
                `${window.location.protocol + "//" + window.location.host}/#/resource/roommeet/${
                    Number(resourceType) === ResourceType.MEETING ? "roommeet" : "roomarea"
                }/submitSuccess/${order.ID}`
            );

            // files.append("ReutrnUrl", this.info.TotalAmount);
            // values.Add("BindTableName", vm.BindTableName);
            // values.Add("Subject", vm.Subject);
            // values.Add("TotalAmount", vm.Amount.ToString());
            // values.Add("BindTableID", vm.BindTableID.ToString());
            // values.Add("TradeChannel", vm.TradeChannel.ToString());
            // values.Add("ParkID", ParkExtensions.GetCurrentParkID()?.ToString());
            // values.Add("ReutrnUrl", AppRuntime.Context.ResolveFullUrl("~/Payment/Success"));

            let result;
            if (Number(payway) === PayWay.alipay) {
                try {
                    // /Cash/Alipay/Pay
                    result = yield call(cashAliPayService.alipay, files);
                    yield put({ type: "input", data: { payBackResult: result } });
                    // document.body.appendChild(result);
                    $(document.body).append(result);
                    // weakthis.goTo(`resourcePaySucceed/${result.id}?bindTableID=${result.id}&payWay=${result.payWay}`);
                } catch (e) {
                    // weakthis.goTo(`resourcePayErr/${e.id}/err`);
                }
            } else if (payway === PayWay.wechat) {
                try {
                    result = yield call(wechatPayService.pay, files);
                    yield put({ type: "input", data: { payBackResult: result, visibleModal: true } });
                    $("#wechatpay").append(result);
                    // weakthis.goTo(`wechatpay`);
                } catch (e) {
                    // weakthis.goTo(`resourcePayErr/${e.id}/err`);
                }
            }
        } catch (e) {
            yield call(error, e);
        } finally {
        }
    }

46、web集成分享

export function shareConfige(text, Desc, url, pic) {
  window._bd_share_config = {
    "common": {
      "bdText": text,
      "bdDesc" : Desc,
      "bdUrl" : url,
      "bdPic": pic,
      "bdSnsKey": {},
      "bdMini": "2",
      "bdMiniList": false,
      "bdStyle": "0",
      "bdSize": "16"
    }, "share": {}
  };

  window._bd_share_main = 0;
  const script = document.createElement("script");
  script.src = "http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion=" + ~(-new Date() / 36e5);
  script.className = "shareconfigure";
  document.body.appendChild(script);
}

47、封装前端注入移动端方法桥接的bridge.js


function aliPay(data) {
    if(data.callback){
        window["callback"]=data.callback.bind(this)
    }
//    window["WebViewJavascriptBridge"].callHandler("aliPay", JSON.stringify(data));
    window["webkit"].messageHandlers.aliPay.postMessage(JSON.stringify(data));
}

function wechatPay(data) {
    if(data.callback){
        window["callback"]=data.callback.bind(this)
    }
//    window["WebViewJavascriptBridge"].callHandler("wechatPay",JSON.stringify(data));
    window["webkit"].messageHandlers.wechatPay.postMessage(JSON.stringify(data));
}

function closeWindow() {
    window["webkit"].messageHandlers.closeWindow.postMessage(JSON.stringify(data));
}

使用

function callback(r) {
        alert(r);
    }

aliPay({ orderInfo: info, aliSign: "123456", callback: callback });

48、前端h5检测检测监听网络状态变化

var el = document.body;  
if (el.addEventListener) {  
   window.addEventListener("online", function () {  
     alert("online");}, true);  
   window.addEventListener("offline", function () {  
     alert("offline");}, true);  
}  
else if (el.attachEvent) {  
   window.attachEvent("ononline", function () {  
     alert("online");});  
   window.attachEvent("onoffline", function () {  
     alert("offline");});  
}  
else {  
   window.ononline = function () {  
     alert("online");};  
   window.onoffline = function () {  
     alert("offline");};  
}

49、html滚动div元素到可见可视范围内

$(ReactDOM.findDOMNode(this.refs[cid as any]) as any)[0].scrollIntoView({behavior: 'smooth'})

50、html滚动到顶部

$(this.refs.scrolref).animate({
	scrollTop: 0
}, 500);

51、webpack打包报javaScript heap out of memory的解决方法(内存报错)
安装:

 npm install -g increase-memory-limit

执行:

 increase-memory-limit

52、antd design Picker组件多级联动

et seasons = [
            {
                label: "河南",
                value: "2013",
                children: [
                    {
                        label: "郑州",
                        value: "123",
                        children: [
                            {
                                label: "金水区",
                                value: "123"
                            },
                            {
                                label: "高新区",
                                value: "456"
                            }
                        ]
                    },
                    {
                        label: "商丘",
                        value: "456"
                    }
                ]
            },
            {
                label: "上海",
                value: "2014",
                children: [
                    {
                        label: "浦东新区",
                        value: "789"
                    },
                    {
                        label: "虹口区",
                        value: "125"
                    }
                ]
            }
        ];
 <Picker data={seasons} title="选择事项类型" extra="请选择(可选)" onChange={value => {}}>
        <InputItem className="list-picker" placeholder="请选择事项类型" editable={false}>
                        事项类型
       </InputItem>
</Picker>

53、css图片背景色调灰色

<img  src={`assets/images/img/${level.IconUrl}`}   style={level.RouteKey === "#" ? { width: 50, height: 50, filter: "grayscale(100%)" } : { width: 50, height: 50}} />

54、公众号几钉钉网页处理图片缓存问题
(1).引用js文件加一个时间戳后缀,如

<script src="xxx/build/main.js?time=132456"></script>

(2).在页面头加入以下代码

<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />

http-equiv介绍
(3)、图片缓存问题

'photo.png?' + Math.random() / 9999

55、node自动化生成iOS企业发布配置文件


auto.js

var dirname = "ceshixiangmu";
var filetype = "alpha2";
var bundleid = "com.bitech.zidonghua.ceshi";
var appname = "测试名称";

var fs = require("fs");
var path = require("path");

fs.mkdir("../" + dirname, function(err) {
  if (err) {
    console.error(err);
  }
  fs.mkdir("../" + dirname + "/" + filetype, function(err) {
    if (err) {
      console.error(err);
    }
    // 根据模版自动创建html文件
    var indexhtml = fs.readFileSync("index.html");
    var indexhtmlstr = indexhtml
      .toString()
      .replace(/dirname/g, dirname)
      .replace(/filetype/g, filetype)
      .replace("bundleid", bundleid)
      .replace("appname", appname);
    fs.writeFileSync(
      "../" + dirname + "/" + filetype + "/" + "index.html",
      indexhtmlstr
    );
    // 根据模版自动创建config文件
    var indexhtml = fs.readFileSync("iOSconfigure.sh");
    var indexhtmlstr = indexhtml
      .toString()
      .replace(/dirname/g, dirname)
      .replace(/filetype/g, filetype);
    fs.writeFileSync(
      "../" + dirname + "/" + filetype + "/" + "iOSconfigure.sh",
      indexhtmlstr
    );
  });
});

index.html


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>items</key>
	<array>
		<dict>
			<key>assets</key>
			<array>
				<dict>
					<key>kind</key>
					<string>display-image</string>
					<key>url</key>
					<string>http://assets.bitech.cn/mobile/ios/dirname/filetype/icon.png</string>
					<key>needs-shine</key>
					<true/>
				</dict>
				<dict>
					<key>kind</key>
					<string>software-package</string>
					<key>url</key>
					<string>http://assets.bitech.cn/mobile/ios/dirname/filetype/index.ipa</string>
				</dict>
			</array>
			<key>metadata</key>
			<dict>
				<key>bundle-identifier</key>
				<string>bundleid</string>
				<key>bundle-version</key>
				<string>1.0.0.1</string>
				<key>kind</key>
				<string>software</string>
				<key>title</key>
				<string>appname</string>
			</dict>
		</dict>
	</array>
</dict>
</plist>

56、微信h5解决input键盘弹起不下落问题
失去焦点时使用下面方法

window.scrollTo(0, 0);

57、h5中iOS客户端图片翻转问题解决


  selectFileImage(files: { file: any; orientation: number; url: string; info: WebUploader.File }[], type: string, index: number) {
    let fileArr = [] as any;
    let _this = this;
    // let file = fileObj.files[0];
    files && files.map((item, index) => {

      let file = item.file,
        Orientation = null;
      if (file) {
        exif.getData(file, function () {

          exif.getAllTags(this);

          Orientation = exif.getTag(this, 'Orientation');
          // console.log(Orientation, this)
          // alert(Orientation);
        });

        let reader = new FileReader();
        reader.readAsDataURL(file);

        reader.onload = function (e) {
          let image = new Image();
          image.src = e.target!.result;
          image.onload = function () {
            let expectWidth = this.naturalWidth;
            let expectHeight = this.naturalHeight;

            if (this.naturalWidth > this.naturalHeight && this.naturalWidth > 800) {
              expectWidth = 800;
              expectHeight = expectWidth * this.naturalHeight / this.naturalWidth;
            } else if (this.naturalHeight > this.naturalWidth && this.naturalHeight > 1200) {
              expectHeight = 1200;
              expectWidth = expectHeight * this.naturalWidth / this.naturalHeight;
            }
            let canvas = document.createElement("canvas");
            let ctx = canvas.getContext("2d");
            canvas.width = expectWidth;
            canvas.height = expectHeight;
            ctx.drawImage(this, 0, 0, expectWidth, expectHeight);
            let base64 = null;
            // 修复ios
            if (navigator.userAgent.match(/iphone/i)) {
              // console.log('iphone');
              // alert(expectWidth + ',' + expectHeight);
              // 如果方向角不为1,都需要进行旋转 added by lzk
              if (Orientation !== "" && Orientation !== 1) {
                // alert('旋转处理');
                switch (Orientation as any) {
                  case 6: // 需要顺时针(向左)90度旋转
                    // alert('需要顺时针(向左)90度旋转');
                    _this.rotateImg(this, 'left', canvas);
                    break;
                  case 8: // 需要逆时针(向右)90度旋转
                    // alert('需要顺时针(向右)90度旋转');
                    _this.rotateImg(this, 'right', canvas);
                    break;
                  case 3: // 需要180度旋转
                    // alert('需要180度旋转');
                    _this.rotateImg(this, 'right', canvas); // 转两次
                    _this.rotateImg(this, 'right', canvas);
                    break;
                  default:
                    break;
                }
              }
              /*var mpImg = new MegaPixImage(image);
              mpImg.render(canvas, {
                  maxWidth: 800,
                  maxHeight: 1200,
                  quality: 0.8,
                  orientation: 8
              });*/
              base64 = canvas.toDataURL("image/jpeg", 0.8);
              let imageFile = _this.dataURLtoFile(base64, new Date().getTime())
              item.file = imageFile;
              fileArr.push(item);
              // console.log(fileArr, files)
              if (index === files.length - 1) {
                // alert("start")
                _this.myOnChange(fileArr, type, index)
              }
            }
          };
        };
      } else {
        fileArr.push(item);
      }
    })
  }
  dataURLtoFile(dataurl: string, filename: string) {
    const arr = dataurl.split(","),
      mime = arr![0]!.match(/:(.*?);/)![1],
      bstr = atob(arr[1]);

    let n = bstr.length;
    const u8arr = new Uint8Array(n);

    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, { type: mime });
  }
  // 对图片旋转处理 added by lzk
  rotateImg(img, direction, canvas) {
    // alert(img);
    // 最小与最大旋转方向,图片旋转4次后回到原方向
    let min_step = 0;
    let max_step = 3;
    // var img = document.getElementById(pid);
    if (img == null) return;
    // img的高度和宽度不能在img元素隐藏后获取,否则会出错
    let height = img.height;
    let width = img.width;
    // var step = img.getAttribute('step');
    let step = 2;
    if (step == null) {
      step = min_step;
    }
    if (direction === 'right') {
      step++;
      // 旋转到原位置,即超过最大值
      step > max_step && (step = min_step);
    } else {
      step--;
      step < min_step && (step = max_step);
    }
    // 旋转角度以弧度值为参数
    let degree = step * 90 * Math.PI / 180;
    let ctx = canvas.getContext('2d');
    switch (step as any) {
      case 0:
        canvas.width = width;
        canvas.height = height;
        ctx.drawImage(img, 0, 0);
        break;
      case 1:
        canvas.width = height;
        canvas.height = width;
        ctx.rotate(degree);
        ctx.drawImage(img, 0, -height);
        break;
      case 2:
        canvas.width = width;
        canvas.height = height;
        ctx.rotate(degree);
        ctx.drawImage(img, -width, -height);
        break;
      case 3:
        canvas.width = height;
        canvas.height = width;
        ctx.rotate(degree);
        ctx.drawImage(img, -width, 0);
        break;
      default:
        break;
    }
  }

  onChange(files: { file: any; orientation: number; url: string; info: WebUploader.File }[], type: string, index: number) {
    const { fileNumLimit } = this.props;

    if (files.length > fileNumLimit) {
      Toast.fail("文件数量超过限制!", 3);
      return;
    }
    if (this.props.fileSuccess) {
      // 有回调就执行,企业认证表单提交会调用
      this.props.fileSuccess(files);
    }
    // console.log("onChange", files, type)
    if (type === "add") {
      this.selectFileImage(files, type, index);

    } else if (type === "remove") {
      const { files: old } = this.state,
        file = old[index],
        { info = file } = file as any;
      this.attachProvider.delFile(info.file || info, this.uploader);
      this.setState({ files } as any);
    }

  }
  myOnChange(files: { file: any; orientation: number; url: string; info: WebUploader.File }[], type: string, index: number) {
    if (this.props.single) {
      const file = files.last();
      this.uploader.once("fileQueued", (info: WebUploader.File) => (((file.info = info), ((info as any).src = file)), this.setState({ files: [file] } as any)));
      this.uploader.addFile(file.file);
    } else {
      files.map((file, index) => {
        if (index >= this.state.files.length) {
          setTimeout(() => {
            this.uploader.once(
              "fileQueued",
              (info: WebUploader.File) => (((file.info = info), ((info as any).src = file)), this.setState({ files: files } as any))
            );
            this.uploader.addFile(file.file);
          });
        }
      });
    }
  }

58、H5固定在底部安卓键盘弹出推上遮挡其他试图去解决方案

let win_h = $(window).height() as any; // 关键代码
            window.addEventListener('resize', function () {
                if ($(window)!.height() as any < win_h) {
                    $('.ether-login').hide();
                } else {
                    $('.ether-login').show();
                }
            });

59、H5中div中指定数量字符换行

                    <div style={{whiteSpace: 'pre'}}>
                        {`测试换行\n测试换行测试换行测试换行测试换行测试换行测试换行`}
                    </div>

60、h5页面readeronly后iOS仍然有键盘头部弹出解决办法

(document.activeElement as any)!.blur();

61、css禁止div中手势操作

pointer-events: none;

62、h5图片上传服务器并经过iOS原生转换图片旋转问题
获取图片file

<input
                                    type="file"
                                    className="my-upload-img-opacity"
                                    accept="image/jpeg,image/jpg,image/png"
                                    multiple={false}
                                    onChange={this.loadAvatarFile.bind(this)}
                                />

        loadAvatarFile(event: Event) {
            event.preventDefault();

            const [file] = (event.target as any).files;

            if (file) {
                if (!/image/i.test(file.type)) {
                    Toast.fail("请选择图片文件。");
                    return;
                }

                this.avatar = null;

                this.dispatch({ type: "input", data: { thumb: URL.createObjectURL(file) } });

                this.avatarAwiat = transformPics(file).then(
                    file => (this.avatar = file),
                    () => (this.avatar = null)
                );
            }
        }


获取iOS转换后的file并创建formData

export function transformPics(file: File) {
  return new Promise((resolve, reject) => {
    file
      ? transformPic(file, { isCompressed: !0 }).then(file => {
        return resolve({file: createData(file), sourcefile: file});
      }, reject)
      : reject();
  });
}

function createData(file: any) {
  const formData = new FormData();

  formData.append("aspectRatio", "80,50");
  formData.append("Image", file, "Image.jpg");
  formData.append("SourceImage", file, "SourceImage" + (/^.*?(\.\w+)$/.exec(file!.name)![1] || ""));
  return formData;
}

从iOS中获取base64串并转换成file文件

function dataURLtoFile(dataurl: string, filename: string) {
    const arr = dataurl.split(","),
        mime = arr![0]!.match(/:(.*?);/)![1],
        bstr = atob(arr[1]);

    let n = bstr.length;
    const u8arr = new Uint8Array(n);

    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, { type: mime });
}

export function transformPic<T>(file: File, options?: T) {
    return new Promise<File>((resolve, reject) => {
        if (file) {
            const { type, name } = file;
            if (/image\//i.test(type) && window["webkit"]) {
                const fileReader = new FileReader();

                fileReader.onload = e => {
                    webkitPostMessage("transformPic", (e.target as any).result, options).then(({ data }) => {
                        return resolve(dataURLtoFile(data, name));
                    }, reject);
                };

                fileReader.readAsDataURL((file as any).source ? (file as any).source : file);

                return;
            }

            resolve(file);
        } else reject(file);
    });
}


63、bitech项目react中禁止Model弹出框左右滑手势交互

setTimeout(() => {
              $('.coupon-modal-popup').on('touchend', (e) => {
                e.stopPropagation();
              }).on('touchmove', (e) => {
                e.stopPropagation();
              })
            }, 500)
            

64、bitech项目中antd使用蚂蚁表单自带验证

<Form onSubmit={this.handleSubmit} className="form-default-style">
                            <Form.Item label="手机号">
                                {getFieldDecorator("phone", {
                                    rules: [{ required: true, message: "手机号不能为空!" }]
                                })(
                                    <Input
                                        size="large"
                                        placeholder="请输入手机号"
                                        onChange={e => {
                                            this.dispatch({ type: "input", data: { phone: e.target.value } });
                                        }}
                                    />
                                )}
                            </Form.Item>
                            <Form.Item label="验证码">
                                <Row gutter={0}>
                                    <Col span={18}>
                                        {getFieldDecorator("code", {
                                            rules: [{ required: true, message: "请输入获取的验证码!" }]
                                        })(
                                            <Input
                                                size="large"
                                                placeholder="请输入验证码"
                                                onChange={e => {
                                                    this.dispatch({ type: "input", data: { code: e.target.value } });
                                                }}
                                            />
                                        )}
                                    </Col>
                                    <Col span={6} className="ant-text-right">
                                        <Button size="large" type="primary">
                                            <Countdown className="size-14 grayColor3" start={this.sendVerifyCode.bind(this)} content="发送验证码" />
                                        </Button>
                                    </Col>
                                </Row>
                            </Form.Item>
                            <Form.Item label="新密码">
                                {getFieldDecorator("password", {
                                    rules: [{ required: true, message: "新密码不能为空!" }, { validator: this.validateToNextPassword }]
                                })(
                                    <Input
                                        size="large"
                                        placeholder="请输入新密码(6-20位,数字、字母组合)"
                                        autoComplete="new-password" // 阻止浏览器在password类型的input中自动赋值
                                        name="password"
                                        type="password"
                                        onChange={e => {
                                            this.dispatch({ type: "input", data: { password: e.target.value } });
                                        }}
                                    />
                                )}
                            </Form.Item>
                            <Form.Item label="确认密码">
                                {getFieldDecorator("confirm", {
                                    rules: [
                                        {
                                            required: true,
                                            message: "确认密码不能为空!"
                                        },
                                        { validator: this.compareToFirstPassword }
                                    ]
                                })(
                                    <Input
                                        size="large"
                                        onBlur={this.handleConfirmBlur}
                                        name="confirm-password"
                                        autoComplete="new-password" // 阻止浏览器在password类型的input中自动赋值
                                        type="password"
                                        placeholder="请再次输入新密码确认"
                                        onChange={e => {
                                            this.dispatch({ type: "input", data: { confirm: e.target.value } });
                                        }}
                                    />
                                )}
                            </Form.Item>
                        </Form>

        compareToFirstPassword = (_rule, value, callback) => {
            const form = (this.props as any).form;

            console.log(222, value)

            if (value && value !== form.getFieldValue("password")) {
                callback("两次输入的密码不一致!");
            } else {
                callback();
            }
        };

        validateToNextPassword = (_rule, value, callback) => {
            const form = (this.props as any).form;
            const { state } = this.props;
            let reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/;

            if (value)
                if (!reg.exec(value)) callback("请输入密码(6-16位字母数字组合)");

            if (state!.get("confirmDirty"))
                form.validateFields(["confirm"], { force: true });

            callback();
        };

65、bitech项目web端开发变更url参数seo


/** 变更Url参数 */
export function changeUrlParams(url: string, params: {}) {

    let index = url.indexOf("?"), isOnlyP = true,
        beforeIndexUrl = index > -1 ? url.substring(0, url.indexOf("?")) : url,
        afterIndexUrl = index > -1 ? url.substring(url.indexOf("?")) : "",
        pIndex = afterIndexUrl.indexOf("p");

    if (pIndex > -1) {
        const afterP = afterIndexUrl.substring(pIndex);
        isOnlyP = afterP.indexOf("&") === -1 ? true : false;
    }

    for (let key in params) {
        if (params.hasOwnProperty(key)) {
            let value = params[key];
            const isValueNull = (typeof (value) === "string" && value.trim() === "") || value === null;
            value = isValueNull ? null : standardEncoding(value);

            if (afterIndexUrl.indexOf("&" + key + "=") > -1 || afterIndexUrl.indexOf("?" + key + "=") > -1) {
                if (isValueNull) {
                    const regex = new RegExp("(&" + key + "=)([^&]*)+", "ig");
                    afterIndexUrl = afterIndexUrl.replace(regex, "");
                } else {
                    const regex = new RegExp("(" + key + "=)([^&]*)+", "ig");
                    afterIndexUrl = afterIndexUrl.replace(regex, function (_matchStr, g1) {
                        return g1 + value;
                    });
                }
            } else {
                if (afterIndexUrl.indexOf("&") === -1) {
                    if (!isValueNull) {
                        const symbol = isOnlyP ? "&" : "?";
                        afterIndexUrl = afterIndexUrl + symbol + key + "=" + value;
                    }
                } else {
                    if (!isValueNull) {
                        afterIndexUrl = afterIndexUrl + "&" + key + "=" + value;
                    }
                }
            }
        }
    }

    url = beforeIndexUrl + afterIndexUrl;
    return url;
}


66、react匹配不到页面跳转错误路由,任意路由

export function notificationRoutes(match: match) {
    return (
        <Route
            path={`${match.path}/notification`}
            render={({ match }) => (
                <>
                    <Route path={match.path} component={Notification.Page} />
                    <Route
                        path={`${match.path}/list/:type`}
                        render={({ match }) => (
                            <>
                                <Route path={match.path} component={NotificationList.Page} />
                                <Switch>
                                    {/* 订单 */}
                                    {orderDetailNotificationRoutes(match)}
                                    {/* 工单 */}
                                    {applyDetailNotificationRoutes(match)}
                                     {/* 匹配不到 */}
                                    {errorRoutes(match)}
                                </Switch>
                            </>
                        )}
                    />
                    {articleDetailRoutes(match)}

                </>
            )}
        />
    );
}

export function errorRoutes(match: match) {
    return (
        <Route
            path={`${match.path}/*`}
            render={({ }) => (
                <Route path={match.path} component={NoticeError.Page} />
            )}
        />
    );
}

67、蚂蚁Tab定制item样式renderTabBar
this.stateTabtem = [] as any;
stateTab && stateTab.map((item) => {
    let tem = { ...item };
    tem.title = <div style={{ fontSize: "12px" }}>{item.name}<span style={{ marginLeft: "5px", color: "red" }}>{item.value}</span></div>
    this.stateTabtem.push(tem)
})
{<Tabs
    key={this.code}
    swipeable={false}
    tabs={this.stateTabtem}
    initialPage={parseInt(order, 10)}
    renderTabBar={props => <div><Tabs.DefaultTabBar {...props} page={3} /></div>}
    onChange={tab => {
        this.code = tab.code;
        this.dispatch({ type: "input", data: { showList: false, FlowStateStatus: tab.name } });
        this.getData({ pageIndex: 1, FlowStateStatus: tab.name });
    }}
>
    {showList ? this.getListView() : <></>}
</Tabs>}
68、react中动态计算宽高方法
<div style={{ width: "calc" + "(" + (item.NoConfirmCount / item.OrderCount) * 100 + "% " + "+" + " 6px" + ")" }}  className="line-bar line-one">
</div>
#div1 {
    position: absolute;
    left: 50px;
    width: calc(100% - 100px);
    border: 1px solid black;
    background-color: yellow;
    padding: 5px;
    text-align: center;
}
69、公众号H5跳转授权
let url = `${location.href.split("/index")[0]}/index/login`;
window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${server.wechatAppid}&redirect_uri=${encodeURIComponent(url)}&response_type=code&scope=snsapi_userinfo#wechat_redirect`;
70、JS转换参数字符串到对象
new URLSearchParams("code=NO_AUTH&message=%E5%95%86%E6%88%B7%E5%8F%B7%E8%AF%A5%E4%BA%A7%E5%93%81%E6%9D%83%E9%99%90%E6%9C%AA%E5%BC%80%E9%80%9A%EF%BC%8C%E8%AF%B7%E5%89%8D%E5%BE%80%E5%95%86%E6%88%B7%E5%B9%B3%E5%8F%B0%3E%E4%BA%A7%E5%93%81%E4%B8%AD%E5%BF%83%E6%A3%80%E6%9F%A5%E5%90%8E%E9%87%8D%E8%AF%95&statusCode=403").get("code")
71、JS提取html模版中的文字
contentHTML && contentHTML.replace(/<\/?.+?\/?>/g, "").replace(/&nbsp;/gi, ""),
72、JS获取浏览器唯一标识
export function WBFingerprint(uid = "", params?) {
    let uidinfo = "";

    if (params) {
        if (params.userAgent) {
            uidinfo = uidinfo + navigator.userAgent;
        }
        if (params.screen) {
            // 屏幕分辨率
            uidinfo = uidinfo + window.screen.height + window.screen.width;
        }
        if (params.platform) {
            // 浏览器的操作系统平台
            uidinfo = uidinfo + navigator.platform;
        }
        if (params.language) {
            // 浏览器语言
            uidinfo = uidinfo + navigator.language;
        }
        if (params.appName) {
            // 浏览器的名称
            uidinfo = uidinfo + navigator.appName;
        }
        if (params.appCodeName) {
            // 浏览器的代码名
            uidinfo = uidinfo + navigator.appCodeName;
        }
        if (uid) {
            // 用户自定义标识
            uidinfo = uidinfo + uid;
        }

    } else {
        uidinfo = navigator.userAgent +
        window.screen.height +
        window.screen.width +
        navigator.platform +
        navigator.language +
        navigator.appName +
        navigator.appCodeName +
        uid
    }

    return btoa(uidinfo);
}

73、html字符串转文字
export function htmlContentTreatWord(content) {
    return content && content.replace(/<\/?.+?\/?>/g, "").replace(/&nbsp;/gi, "");
}
75、

持续更新中…

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值