JS十

字符串,匀速运动

url网址编码

1
2
3
4
var url = "http://www.itcast.cn?name=andy";
console.log(encodeURIComponent(url)); // 编码
var afterUrl = encodeURIComponent(url);
console.log(decodeURIComponent(afterUrl)); // 解码

连接字符串

html

1
2
<div id="div1">my name is andy!</div>
<div id="div2">what's your name?</div>

script

1
2
3
var div1 = document.getElementById("div1").innerHTML;
var div2 = document.getElementById("div2").innerHTML;
console.log(div1.concat(div2));

保留小数点后2位

1
2
3
4
5
6
7
8
9
var PI = 1213.141592653; // 常量大写
var str = PI + ""; // 因为数字没法进行字符操作 先转换
var index = str.indexOf("."); // 我们要返回当前字符的点的位置 indexOf(".")
console.log(index);
console.log(str.substr(0,index+3));
console.log(str.substr(0,str.indexOf(".")+3));
console.log(parseInt(PI*100) /100);
//1213.141592653 * 100 = 121314.1592653 取整 121314 /100
console.log(PI.toFixed(2));

转换大小写

html

1
2
3
<h1 id="big">这是大标题</h1>
<p id="small">这个是小标题</p>
<input type="text" id="txt"/> <button id="btn">发布</button>

script

1
2
3
4
5
function $(id) { return document.getElementById(id)}
$("btn").onclick = function(){
$("big").innerHTML = $("txt").value.toUpperCase();
$("small").innerHTML = $("txt").value.toLowerCase();
}

匀速运动

html

1
2
<button id="btn">开始</button>
<div class="box" id="bOX"></div>

css

1
2
3
4
5
6
7
8
.box {
position: absolute;
top:100px;
left:0;
width: 100px;
height: 100px;
background-color: pink;
}

script

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var btn = document.getElementById("btn");
var box = document.getElementById("bOX");
var num = 0;
var timer = null;
btn.onclick = function() {
timer = setInterval(function(){
num++;
if(num >=500)
{
clearInterval(timer);
}
else
{
box.style.left = num + "px";
}
},10)
}

正确上传图片文件格式

html

1
<input type="file" name="" id="File"/><span></span>