1. parseInt(“08”),parseInt("09") 输出0 (IE 8)
使用parseInt("08",10)
2. 不支持indexOf (IE 8)
if(!Array.indexOf){
Array.prototype.indexOf = function(obj){
for(var i=0; i<this.length; i++){
if(this[i]==obj){
return i;
}
}
return -1;
}
}
3. toFixed 不四舍五入
function changeDecimal(num, bitNum) {
var bb = num+"";
var dian = bb.indexOf('.');
var result = "";
if(dian == -1){
result = num.toFixed(bitNum);
}else{
var cc = bb.substring(dian+1,bb.length);
if(cc.length >=bitNum){
result =bb.substring(0,dian+bitNum+1)
//result = (Number(num.toFixed(bitNum))+0.01)*100000000000/100000000000;//js小数计算小数点后显示多位小数
}else{
result = num.toFixed(bitNum);
}
}
return result;
}
4. 左右滚动广告
window.setInterval(function () {
var context = $("#broadcast_content");
var left = parseFloat(context.css('left'));
var length = context.text().length * 18*(-1);//18wei为font-size
if (left > length) {
context.css({ "left": left - 1 });
} else {
context.css({ "left":"450px"});//可见kuang框kuandu
}
}, 40);
5.随机抽奖
(function(){
function rd(n,m){
var c = m-n+1;
return Math.floor(Math.random() * c + n);
}
setInterval(function getRandomInfo(){
var ln ="赵,钱,孙,李,周,吴,郑,王,冯,陈,楮,卫,蒋,沈,韩,杨,朱,秦,尤,许,何,吕,施,张,孔,曹,严,华,金,魏,陶,姜,戚,谢,邹,喻,柏,水,窦,章,云,苏,潘,葛,奚,范,彭,郎,鲁,韦,昌,马,苗,凤,花,方,俞,任,袁,柳,酆,鲍,史,唐,费,廉,岑,薛,雷,贺,倪,汤,滕,殷,罗,毕,郝,邬,安,常,乐,于,时,傅,皮,卞,齐,康,伍,余,元,卜,顾,孟,平,黄,和,穆,萧,尹,姚,邵,湛,汪,祁,毛,禹,狄,米,贝,明,臧,计,伏,成,戴,谈,宋,茅,庞,熊,纪,舒,屈,项,祝,董,梁,杜,阮,蓝,闽,席,季,麻,强,贾,路,娄,危,江,童,颜,郭,梅,盛,林,刁,锺,徐,丘,骆,高,夏,蔡,田,樊,胡,凌,霍,虞,万,支,柯,昝,管,卢,莫,经,房,裘,缪,干,解,应,宗,丁,宣,贲,邓,郁,单,杭,洪,包,诸,左,石,崔,吉,钮,龚,程,嵇,邢,滑,裴,陆,荣,翁,荀,羊,於,惠,甄,麹,家,封,芮,羿,储,靳,汲,邴,糜,松,井,段,富,巫,乌,焦,巴,弓,牧,隗,山,谷,车,侯,宓,蓬,全,郗,班,仰,秋,仲,伊,宫,宁,仇,栾,暴,甘,斜,厉,戎,祖,武,符,刘,景,詹,束,龙,叶,幸,司,韶,郜,黎,蓟,薄,印,宿,白,怀,蒲,邰,从,鄂,索,咸,籍,赖,卓,蔺,屠,蒙,池,乔,阴,郁,胥,能,苍,双,闻,莘,党,翟,谭,贡,劳,逄,姬,申,扶,堵,冉,宰,郦,雍,郤,璩,桑,桂,濮,牛,寿,通,边,扈,燕,冀,郏,浦,尚,农,温,别,庄,晏,柴,瞿,阎,充,慕,连,茹,习,宦,艾,鱼,容,向,古,易,慎,戈,廖,庾,终,暨,居,衡,步,都,耿,满,弘,匡,国,文,寇,广,禄,阙,东,欧,殳,沃,利,蔚,越,夔,隆,师,巩,厍,聂,晁,勾,敖,融,冷,訾,辛,阚,那,简,饶,空,曾,毋,沙,乜,养,鞠,须,丰,巢,关,蒯,相,查,后,荆,红,游,竺,权,逑,盖,益,桓,公,万俟,司马,上官,欧阳,夏侯,诸葛,闻人,东方,赫连,皇甫,尉迟,公羊,澹台,公冶,宗政,濮阳,淳于,单于,太叔,申屠,公孙,仲孙,轩辕,令狐,锺离,宇文,长孙,慕容,鲜于,闾丘,司徒,司空,丌官,司寇,仉,督,子车,颛孙,端木,巫马,公西,漆雕,乐正,壤驷,公良,拓拔,夹谷,宰父,谷梁,晋,楚,阎,法,汝,鄢,涂,钦,段干,百里,东郭,南门,呼延,归,海,羊舌,微生,岳,帅,缑,亢,况,后,有,琴,梁丘,左丘,东门,西门,商,牟,佘,佴,伯,赏,南宫,墨,哈,谯,笪,年,爱,阳,佟";
var nameList = ln.split(',');
var gender = ["先生","女士"];
var multiple = rd(3,6);
var result = nameList[rd(0,nameList.length-1)] + gender[rd(0,1)]+' 抽到了幸运奖'+multiple+'个神兜兜';
console.log(result);
},1000)
}
)();
6.字符串和数字之间的隐式强制类型转换 (from 你不知道的javascript)
var a = "42";
var b = "0";
var c = 42;
var d = 0;
a + b; // "420"
c + d; // 42
var a = [1,2];
var b = [3,4];
a + b; // "1,23,4"
var a = 42;
var b = a + "";
b; // "42"
//a + ""(隐式)和前面的String(a)(显式)之间有一个细微的差别需要注意。根据
//ToPrimitive 抽象操作规则,a + "" 会对a 调用valueOf() 方法,然后通过ToString 抽象
//操作将返回值转换为字符串。而String(a) 则是直接调用ToString()。
//它们最后返回的都是字符串,但如果a 是对象而非数字结果可能会不一样!
var a = {
valueOf: function() { return 42; },
toString: function() { return 4; }
};
a + ""; // "42"
String( a ); // "4"
var a = [3];
var b = [1];
a - b; // 2
//为了执行减法运算,a 和b 都需要被转换为数字,它们首先被转换为字符串(通过
//强制类型转换 toString()),然后再转换为数字。
7.全局DOM 变量 (from 你不知道的javascript)
在创建带有id 属性
的DOM 元素时也会创建同名的全局变量。例如:
<div id="foo"></div>
以及:
if (typeof foo == "undefined") {
foo = 42; // 永远也不会运行
}
console.log( foo ); // HTML元素
8.滚动定位到指定位置
$("html,body").animate({scrollTop:$("#" + id).offset().top}, 800); //动态获取元素的高度在滚动至该高度
9.动态设置字体大小(rem)
设置meta: <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
var calculate_size = function() {
// var BASE_FONT_SIZE = 100;
var docEl = document.documentElement,
clientWidth = document.querySelector(".container").clientWidth;
if (!clientWidth) return;
docEl.style.fontSize = (clientWidth / 10) + 'px';
};
// Abort if browser does not support addEventListener
if (document.addEventListener) {
var resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize';
window.addEventListener(resizeEvt, calculate_size, false);
document.addEventListener('DOMContentLoaded', calculate_size, false);
calculate_size();
}
10.格式化金额
//计算器
function fmoney(s, n) {
n = n > 0 && n <= 20 ? n : 2;
s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
var l = s.split(".")[0].split("").reverse(),
r = s.split(".")[1];
t = "";
for (i = 0; i < l.length; i++) {
t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
}
return t.split("").reverse().join("");
//return t.split("").reverse().join("") + "." + r;
}
function GetMoney(moneyval) {
var fomatmoney = "";
var reg = new RegExp(",", "g"); //创建正则RegExp对象
moneyval = moneyval.replace(reg, "");
if (moneyval.length > 9) {
moneyval = parseInt(moneyval / 100) + "";
}
if (isNaN(moneyval) || moneyval == "") {
document.getElementById("moneytxt").value = "";
document.getElementById("money").innerHTML = "0";
return;
}
if (isNaN(moneyval) || moneyval.length < 1) {
if (parseFloat(moneyval) < 1) {
alert("数字不能小于1!");
return;
}
alert("请输入数字!");
return;
}
if (moneyval === " ") {
console.log("error");
document.getElementById("moneytxt").value = "";
return;
}
var fomatmoney = fmoney(moneyval, 0);
document.getElementById("moneytxt").value = fomatmoney;
document.getElementById("money").innerHTML = parseInt(moneyval * 5 / 1000) > 50000?50000:parseInt(moneyval * 5 / 1000);
//if (isNaN(moneyval) || moneyval.length < 4) {
// document.getElementById("money").innerHTML = parseInt(0);
//}
}
11.判断iframe是否加载成功:
iframe.onload = function(){
var that = $(this)[0];
try{
that.contentDocument;
}
catch(err){
//TODO
}
}
12.Knockout 使用jquery直接赋值不被监听
使用change方法: $("#id").val("testValue").change()
13.点击其他区域关闭某区域
$(document).mouseup(function(e){
var _con = $(' 目标区域 '); // 设置目标区域
if(!_con.is(e.target) && _con.has(e.target).length === 0){ // Mark 1
some code... // 功能代码
}
});
/* Mark 1 的原理:
判断点击事件发生在区域外的条件是:
1. 点击事件的对象不是目标区域本身
2. 事件对象同时也不是目标区域的子元素
*/
14.图片转blob,base64 (React Croper)
<AvatarSelector
src={this.props.profileSettings.photo}
onChange={this.onAvatarSelectorChange}
onChangeIllegalType={this.onChangeIllegalType}
inputProps={{name: 'wort-wort-wort'}}
isLoading={this.props.profileSettings.isLoading}
size = "150px"
/>
<div onClick = {this.chooseImg}>
<ReactCrop
src={this.state.src}
crop={this.state.crop}
onImageLoaded={this.onImageLoaded}
onComplete={this.onCropComplete}
onChange={this.onCropChange}
/>
</div>
onCropChange = (crop:any) => {
this.setState({crop:crop});
};
onImageLoaded = (image:any):void => {
this.imageRef = image;
};
onCropComplete = async (crop:any, pixelCrop:any) => {
if (crop.width && crop.height) {
const croppedImageUrl = await this.getCroppedImg(
this.imageRef,
pixelCrop,
'newFile.jpeg',
);
this.setState({croppedImageUrl:croppedImageUrl });
}
};
chooseImg = (e:any)=>{
e.preventDefault();
let now = new Date().getTime();
if( now - this.touchTime < 500){
this.touchTime = now;
this.handlePhotoChange();
}else{
this.touchTime = now;
}
// this.resetValidation();
}
getCroppedImg(image:any, pixelCrop:any, fileName:any) {
const canvas = document.createElement('canvas');
canvas.width = pixelCrop.width;
canvas.height = pixelCrop.height;
const ctx = canvas.getContext('2d');
(ctx as any).drawImage(
image,
pixelCrop.x,
pixelCrop.y,
pixelCrop.width,
pixelCrop.height,
0,
0,
pixelCrop.width,
pixelCrop.height,
);
return new Promise((resolve, reject) => {
canvas.toBlob((blob:any) => {
blob.name = fileName;
this.imageBlob = blob;
window.URL.revokeObjectURL(this.fileUrl);
this.fileUrl = window.URL.createObjectURL(blob);
//Convert to base64
var dataURL = canvas.toDataURL('image/png');
this.base64Url = dataURL;
resolve(this.base64Url);
}, 'image/jpeg');
});
}
15.倒计时
function show_timese(t1, now, target) {//目标时间,现在时间,目标元素
var temp;
if (t1 - now > 0) {
temp = t1 - now;
} else {
temp = 1;
}
// 天
var int_day = Math.floor(temp / 86400000)
temp -= int_day * 86400000;
// 时
var int_hour = Math.floor(temp / 3600000)
temp -= int_hour * 3600000;
// 分
var int_minute = Math.floor(temp / 60000)
temp -= int_minute * 60000;
// 秒
var int_second = Math.floor(temp / 1000)
}
//调用
setInterval(function() {
show_timese(time1, time_now, target);
}, 60000)
16.js动态加载
var JsLoader = function(sUrl, fCallback) {
var _script = document.createElement('script');
_script.setAttribute('type', 'text/javascript');
_script.setAttribute('src', sUrl);
document.getElementsByTagName('head')[0].appendChild(_script);
if (_script.addEventListener) {
_script.onload = function() {
_script.parentNode.removeChild(_script);
fCallback && fCallback();
}
} else if (_script.readyState) {
_script.onreadystatechange = function() {
if (_script.readyState == 'loaded' || _script.readyState == 'complete') {
_script.onreadystatechange = null;
_script.parentNode.removeChild(_script);
fCallback && fCallback();
}
}
} else {
_script.parentNode.removeChild(_script);
}
};
17.获取特定url链接属性
function getQueryString(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg);
if (r != null) return unescape(r[2]);
return null;
}
18. svg在ie下做背景图得时候background-position失效
检查svg是否设置了width,height及合适得viewbox
19.Git 倒出带历史记录的repo
gitremote add origin XXXXXXXXX
gitpush -u origin –all
在本地创建分支dev并切换到该分支
git checkout -b dev(本地分支名称) origin/dev(远程分支名称)
20.chrome设置跨域
新建一个chrome快捷方式,右击属性,快捷方式,目标,添加 --disable-web-security --user-data-dir="C:/blabla"
("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="C:/blabla")
21.Print
1) new window
let html = document.querySelector(".print-area").innerHTML;
let myWindow=window.open('','','width='+(window.screen.availWidth-10)+',height='+(window.screen.availHeight-30)+',top=0,left=0,toolbars=no,scrollbars=no,status=no');
myWindow.document.write(html);
myWindow.document.close();
myWindow.focus();
myWindow.print();
myWindow.close();
1) Iframe
var iframe=document.getElementById("print-iframe") as any;
if(!iframe){
// var el = document.getElementById("printcontent");
iframe = document.createElement('IFRAME');
var doc = null;
iframe.setAttribute("id", "print-iframe");
iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:-500px;top:-500px;');
document.body.appendChild(iframe);
doc = iframe.contentWindow.document;
//这里可以自定义样式
//doc.write("<LINK rel="stylesheet" type="text/css" href="css/print.css">");
doc.write('<div>' + document.documentElement.innerHTML + '</div>');
doc.close();
iframe.contentWindow.focus();
}
iframe.contentWindow.print();
if (navigator.userAgent.indexOf("MSIE") > 0){
document.body.removeChild(iframe);
}
22. Email outlook 圆角
<!--[if mso]>
<v:roundrect xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w="urn:schemas-microsoft-com:office:word" href="{{marketplaceUrl}}" style="border-radius:8px;v-text-anchor:middle;width:166px;height:45px;" arcsize="10%" strokecolor="#ffffff" strokeweight ="0px" fillcolor="#002A3E"> <v:stroke dashstyle="solid" /> <w:anchorlock/> <center style="color:#ffffff;font-family:Arial,Helvetica,sans-serif;font-size:11pt;font-weight:bold;">Go to Marketplace</center> </v:roundrect>
<![endif]-->
<!--[if !mso]> <!---->
<table style="background-color:#002A3E;border-radius:5px;border:none;display:inline-block;font-size:16px;font-weight:normal;letter-spacing:0px;line-height:16px;padding:11px 12px 11px 12px;font-weight:600"> <tr> <td> <a style="color:#FFF;text-decoration:none" href={{marketplaceUrl}} target="_blank">Go to Marketplace</a> </td> </tr> </table>
<!-- <![endif]-->