function imgLoad(src){
var img = new Image();
if(img.complete){ //從緩存里面取
callback();
}else{
img.onload = function(){ //實際加載完成
callback();
}
}
img.src = src;
}
實現類似于add(1)(2)(3)調用
function add(x){
var sum = x;
var tmp = function(y){
sum = sum + y;
return tmp;
}
tmp.toString = function(){
return sum;
}
return tmp
}
用代碼來畫個國旗
js獲取URL中的參數
function getQueryString(url, name) {
var reg = new RegExp("(^|&|?)" + name + "=([^&]*)(&|$)", "i");
var r = url.substr(1).match(reg);
if (r != null) return unescape(r[2]); return null;
}
// 創建一個額外的a標簽
function parseURL(url) {
var a = document.createElement("a");
a.href = url;
return {
source: url,
protocol: a.protocol.replace(":",""),
host: a.hostname,
port: a.port,
query: a.search,
params: (function(){
var ret = {},
seg = a.search.replace(/^?/,"").split("&"),
len = seg.length, i = 0, s;
for (;ijavascript如何添加前置0
function addPreZero(num){
return ("000000000"+num).slice(-10);
}
html5實現圖片預覽和查看原圖
var upimg = document.querySelector("#upimg");
upimg.addEventListener("change", function(e){
var files = this.files;
if(files.length){
// 對文件進行處理,下面會講解checkFile()會做什么
checkFile(this.files);
}
});
// 圖片處理
function checkFile(files){
var file = files[0];
var reader = new FileReader();
// show表示,用來展示圖片預覽的
if(!/image/w+/.test(file.type)){
show.innerHTML = "請確保文件為圖像類型";
return false;
}
// onload是異步操作
reader.onload = function(e){
show.innerHTML = "";
}
}
判斷 x 是否是整數
function isInteger(x) {
return parseInt(x, 10) === x;
}
function add(x, y) {
return x.toPrecision() + y.toPrecision()
}
console.log(add(0.1,0.2));
function add(num1, num2){
let r1, r2, m;
r1 = (""+num1).split(".")[1].length;
r2 = (""+num2).split(".")[1].length;
m = Math.pow(10,Math.max(r1,r2));
return (num1 * m + num2 * m) / m;
}
console.log(add(0.1,0.2)); //0.3
console.log(add(0.15,0.2256)); //0.3756
var copyEmailBtn = document.querySelector(".js-emailcopybtn");
copyEmailBtn.addEventListener("click", function(event) {
// Select the email link anchor text
var emailLink = document.querySelector(".js-emaillink");
var range = document.createRange();
range.selectNode(emailLink);
window.getSelection().addRange(range);
try {
// Now that we"ve selected the anchor text, execute the copy command
var successful = document.execCommand("copy");
var msg = successful ? "successful" : "unsuccessful";
console.log("Copy email command was " + msg);
} catch(err) {
console.log("Oops, unable to copy");
}
// Remove the selections - NOTE: Should use
// removeRange(range) when it is supported
window.getSelection().removeAllRanges();
});
var count = (function() {
var timer;
var i = 0;
function change(tar) {
i++;
console.log(i);
if (i === tar) {
clearTimeout(timer);
return false;
}
timer = setTimeout(function() {
change(tar)
}, 1000)
}
return change;
})()
count(50)
onerror log
"use strict";
function errorHandler( message, source, lineno, colno, error){
var errorDiv = document.getElementById("error");
errorDiv.classList.remove("hide");
console.log("Error happened, message:", message);
console.log("On source file: ", source);
console.log("On line - col: ", lineno, "-", colno);
console.log("Error:", error);
try {
var ua = navigator.userAgent;
console.log("UA: ", ua);
} catch (e) {
console.log("Unable to get UA");
}
}
window.onerror = errorHandler;
javascript copy
BBCode
"use strict";
function addCopyEventListener(url){
var divs = document.querySelectorAll("div.copyAsText");
for (var index in divs) {
if(!divs.hasOwnProperty(index)) {
continue;
}
var div = divs[index];
var input = div.querySelector("input");
var btn = div.querySelector("label");
if (url !== "") {
var template = input.getAttribute("data-template");
input.value = template.replace("${url}", url);
}
void function(btn, input){
btn.addEventListener("click", function(){
if (btn.disabled) {
return;
}
var res = false;
try {
input.disabled = false;
var section = window.getSelection();
section.removeAllRanges();
input.focus();
input.setSelectionRange(0, input.value.length);
res = document.execCommand("copy");
input.disabled = true
} catch(e) {
res = false;
}
if (res) {
var origin = btn.textContent;
btn.textContent = "Copied!";
btn.disabled = true;
setTimeout(function(){
btn.textContent = origin;
btn.disabled = false;
}, 2000);
} else {
window.prompt("Copy to clipboard: Ctrl+C, Enter", input.value);
}
});
}(btn, input);
}
}
addCopyEventListener("");
//https://github.com/imsobear/blog/issues/31
//只需要對相應的元素綁定 mouseenter 的事件,然后響應 selectText() 這個方法就 ok
function selectText (element) {
var text = element,
range,
selection;
if (body.createTextRange) {
// IE
range = body.createTextRange();
range.moveToElementText(text);
range.select();
} else if (window.getSelection) {
// Others
selection = window.getSelection();
range = doc.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
} else {
return false;
}
}
把節點列表(NodeList)轉換為數組
var elements = document.querySelectorAll("p"); // NodeList
var arrayElements = [].slice.call(elements); // 現在 NodeList 是一個數組
var arrayElements = Array.from(elements); // 這是另一種轉換 NodeList 到 Array 的方法
var array1 = [1,2,3];
var array2 = [4,5,6];
console.log(array1.push.apply(array1, array2)); // [1,2,3,4,5,6];
JavaScript實現字符串長度截取
function cutstr(str, len) {
var temp;
var icount = 0;
var patrn = /[^x00-xff]/;
var strre = "";
for (var i = 0; i < str.length; i++) {
if (icount < len - 1) {
temp = str.substr(i, 1);
if (patrn.exec(temp) == null) {
icount = icount + 1
} else {
icount = icount + 2
}
strre += temp
} else {
break
}
}
return strre + "..."
}
function $(id) {
return !id ? null : document.getElementById(id);
}
// 用法:如果地址是 test.htm?t1=1&t2=2&t3=3, 那么能取得:GET["t1"], GET["t2"], GET["t3"]
function get_get(){
querystr = window.location.href.split("?")
if(querystr[1]){
GETs = querystr[1].split("&")
GET =new Array()
for(i=0;i 100) ? "block": "none"
}
};
backTop("goTop");
mockjs讓前端開發獨立于后端
rand num
function GetRandomNum(Min,Max)
{
var Range = Max - Min;
var Rand = Math.random();
return(Min + Math.round(Rand * Range));
}
var num = GetRandomNum(10,100);
如果某個操作數為 true ,則該操作數之后的操作數都不會被計算 如果邏輯與和邏輯或作混合運算,則邏輯與的優先級高 if 中,[] 和 {} 都表現為 true
Unicode 編碼轉換
function encodeUTF8(str){
var temp = "",rs = "";
for( var i=0 , len = str.length; i < len; i++ ){
temp = str.charCodeAt(i).toString(16);
rs += "u"+ new Array(5-temp.length).join("0") + temp;
}
return rs;
}
function decodeUTF8(str){
return str.replace(/(u)(w{4}|w{2})/gi, function($0,$1,$2){
return String.fromCharCode(parseInt($2,16));
});
}
encodeUTF8("中文")
"u4e2du6587"
decodeUTF8("u4e2du6587")
"中文"
//https://segmentfault.com/q/1010000000095710
var decToHex = function(str) {
var res=[];
for(var i=0;i < str.length;i++)
res[i]=("00"+str.charCodeAt(i).toString(16)).slice(-4);
return "u"+res.join("u");
}
var hexToDec = function(str) {
str=str.replace(//g,"%");
return unescape(str);
}
var decodeHtmlEntity = function(str) {
return str.replace(/(d+);/g, function(match, dec) {
return String.fromCharCode(dec);
});
};
var str = "JavaScript高级程序设计";
console.log(decodeHtmlEntity(str));//JavaScript高級程序設計
var encodeHtmlEntity = function(str) {
var buf = [];
for (var i=str.length-1;i>=0;i--) {
buf.unshift(["", str[i].charCodeAt(), ";"].join(""));
}
return buf.join("");
};
var str = "高級程序設計";
console.log(encodeHtmlEntity(str));//高级程序设计
function u2str(text){
return $("").html(text).text();
}
數組反轉
var test = [
[1, 0, 4, 3, 2],
[0, 4, 3, 2, 1],
[4, 3, 2, 1, 0],
[3, 2, 1, 0, 4]
];
test.forEach(arr => console.log(reversal(arr)));
// 反轉
function reversal(arr) {
let len = arr.length;
// get max
let max = arr[0];
let index = 0;
arr.forEach((v, i) => {
if (v <= max) return;
max = v;
index = i;
});
// strat re
let tmp = arr.reverse().concat(arr, arr);
let newIndex = len - 1 - index + len;
return tmp.slice(newIndex - index, newIndex + len - index);
}
var arr = [1, 0, 4, 3, 2];
反轉為
var arr = [2, 3, 4, 0, 1];