前端常用数据处理的简单工具方法总结
文件 util.js
/**
* 实现字符串按照长度截取
* @param str [string]
* @returns len [number]
* get string length ,include letter、number、symbol and Chinese Word. a Chiness word has 2 unit length
*/
getStrLen = str => {
var len = 0
for ( var i = 0; i < str.length; i++ ) {
if ( str.charCodeAt( i ) > 127 || str.charCodeAt( i ) == 94 ) {
len += 2
} else {
len++
}
}
return len
},
subStr = ( str, len ) => {
let _str = "",
_len = 0
if ( str && str.length > 0 ) {
if ( str.length === getStrLen( str ) ) {
_str = str.substr( 0, len )
} else {
let index = 0
for ( var i = 0; i < str.length; i++ ) {
if ( str.charCodeAt( i ) > 127 || str.charCodeAt( i ) == 94 ) {
_len += 2
} else {
_len++
}
if ( len === _len ) {
index = i
break
}
}
_str = str.substr( 0, index )
}
}
return _str
}
/**
* 获取元素的位置
* @param {element} element
* @param {string or array} position
*/
export function getElementPosition(element, position) {
let infoObj = element.getBoundingClientRect();
if (typeof position === 'string') {
return infoObj[position];
} else if (Array.isArray(position)) {
let obj = {};
position.map((item, index) => {
return obj[item] = infoObj[item];
})
return obj;
}
}
/**
* 将指定元素滑到可视区域
* ele:'activeVisibleNode'
* parentEle:"perSectionContainer"
*/
export function scrollIntoView(ele, viewEle) {
if (!ele || !viewEle) return;
const tartgetObj = getElementPosition(ele, ['top', 'bottom']);
const targetTop = tartgetObj.top;
const targetBottom = tartgetObj.bottom;
const scrollViewObj = getElementPosition(viewEle, ['top', 'bottom']);
const scrollViewTop = scrollViewObj.top;
const scrollViewBottom = scrollViewObj.bottom;
const windowEle = document.documentElement;
const windowBottom = windowEle.offsetHeight;
let topHeight = 226;
let bottomHeight = 130;
let paddingTop = 50;
if (targetTop < 226 || targetBottom > (windowBottom - bottomHeight)) {
let top = viewEle.scrollTop + targetTop - scrollViewTop;
// console.log('-----不在可视区域',targetTop, top,targetBottom)
window.scrollTo({ behavior: 'smooth', left: 0, top: top })
}
if (targetTop < scrollViewTop || targetBottom > (scrollViewBottom - bottomHeight)) {/** 阅读布局 */
let top = viewEle.scrollTop + targetTop - scrollViewTop - 60;
// console.log('-----不在可视区域----', top)
viewEle.scrollTo({ behavior: 'smooth', left: 0, top: top })
}
}
/**
* 获取具体时间
* @param {*} date
*/
export function timeDetail(d) {
let date = new Date(d);
let year = date.getFullYear();
let month = date.getMonth();
let day = date.getDate();
let _time = date.getTime();
return { date, _time, year, month, day }
}
/**
* ios时间处理
* @param {*} str
*/
export function formatIosTime(str) {
let dateTmp = str.replace(/-/g, '/').split(".")[0] //为了兼容ios
let date = (new Date(dateTmp.replace(/T/g, ' ')));
return date;
}
/**
* 日期转换年月日时分秒
* @param: timestamp, typeof: Number
*/
const transTime = (timestamp) => {
let nowTemp = Date.parse(new Date())
let reduceTemp = nowTemp - timestamp
let years = reduceTemp < 1000 * 60 * 60 * 24 * 365 ? 0 : parseInt(reduceTemp / (1000 * 60 * 60 * 24 * 365))
let days = parseInt(reduceTemp / (1000 * 60 * 60 * 24))
let hours = parseInt((reduceTemp % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
let minutes = parseInt((reduceTemp % (1000 * 60 * 60)) / (1000 * 60))
let seconds = (reduceTemp % (1000 * 60)) / 1000
return { years, days, hours, minutes, seconds }
}
// 判断常见移动端浏览器类型
const ua = window.navigator.userAgent;
export const isAndroid = ua.indexOf('Android') > -1 || ua.indexOf('Adr') > -1; //android终端
export const isiOS = !!ua.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
export const isWeibo = /WeiBo/i.test(ua); //微博
export const isWechat = /MicroMessenger/i.test(ua); //微信
export const isAlipay = /AlipayClient/i.test(ua); //支付宝
//h5 跟移动端混合开发交互 hybrid.js
//Android register
function androidInitWebViewJavascriptBridge(callback) {
if (window.WebViewJavascriptBridge) {
callback(window.WebViewJavascriptBridge)
} else {
document.addEventListener('WebViewJavascriptBridgeReady', function () {
callback(window.WebViewJavascriptBridge);
},
false
);
}
}
androidInitWebViewJavascriptBridge(function (bridge) {
bridge.init(function (message, responseCallback) {
responseCallback && responseCallback('response message from js');
});
registerFuncs(bridge)
})
//IOS register
function iOSInitWebViewJavascriptBridge(callback) {
if (window.WebViewJavascriptBridge) { return callback(window.WebViewJavascriptBridge); }
if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); }
window.WVJBCallbacks = [callback];
var WVJBIframe = document.createElement('iframe');
WVJBIframe.style.display = 'none';
WVJBIframe.src = 'https://__bridge_loaded__';
document.documentElement.appendChild(WVJBIframe);
setTimeout(function () { document.documentElement.removeChild(WVJBIframe) }, 0);
}
iOSInitWebViewJavascriptBridge(function (bridge) {
registerFuncs(bridge)
})
// 用法
/**
* h5调app方法--通用方法
* @param {*} funcName
* @param {*} payload
*/
export const commonHybridFunc = (funcName, payload = {}) => {
let iosBridge = window.webkit;
let androidBridge = window.WebViewJavascriptBridge;
if (checkPhoneOs()) {/** ios */
iosBridge && iosBridge.messageHandlers[funcName].postMessage({ ...payload });
} else {/** android */
console.log('androidBridge:', androidBridge)
return new Promise(resolve => {
androidBridge && androidBridge.callHandler(funcName, { ...payload }, (res) => {
console.log('android res', res)
resolve(res)
})
})
}
}
// 外部调用方法
export const demoF = (mode, params) => {
commonHybridFunc("functionName", params)
}
// 参考博客
https://blog.csdn.net/weixin_44696379/article/details/103327042
shimuqiao

浙公网安备 33010602011771号