1.window.alert vs. window.confirm
(1)window.alert:只能确认
window.alert("第一次alert"); alert("第二次alert"); //window可省略
(2)window.confirm:有同意或取消 会回传值
var temp = window.confirm("今天下大雨"); console.log(temp);
2.setInterval 与 setTimeout 差异
setTimeout做了就不回头(似烟火)
setInterval 计时秒数器
setInterval(function () { cat = cat + 1; console.log(`累计秒数: ${cat} `); }, 1000);
setTimeout 更新网址
setTimeout(function () { document.location.href = "https://one-piece.com/"; }, 3000);
3.取得CSS内的属性(查询CSS元素内,属性的预设)
var elm = document.getElementById("cat"); console.log(elm); // 是一个 img 元素
(1)元素.style.top 取得 样式 top 值
必须自己有写CSS才抓的到
var x = elm.style.top; console.log(`X 的值在这里 => ${x} <=`);
(2)透过 window.getComputedStyle(CSS元素).getPropertyValue('属性'))--------->大绝招抓抓
「预设」的也看的到,所以使用这个!!
var y = window.getComputedStyle(elm).getPropertyValue("top"); console.log(`y 的值在这里 => ${y} <=`); //auto
4.不要使用重複id的原因
只会抓第一个,所以id才说不要重複使用!!
<!-- 错误示範 不要使用重複id --> <h2 id="myApple">Apple</h2> <h2 id="myApple">Apple-1</h2>
result = document.getElementById("myApple"); console.log(result);
5.掏空仓库
预想未来要装甚么
result = 0 数字
result = [] 阵列
result = 字串
5.-1 禁止空字串,因为未来很难抓bug
错误
var x = ""; //使值初始化
正确:先给值
var x = 0;var x = "这里是文字";
undefined 未来会很难抓 以防程式码变多 debug 困难
""是初始化,javascript 没有初始化也可以,但最好是有
因为没初始化的话,其值会是undefined
6.抓阵列[]
var deng = document.images; if (mybool) { deng[0].src = "like.png"; //抓阵列第一个[0][1] mybool = false; } else { deng[0].src = "find.png"; mybool = true; }
7.抓图片位置后,切换图片
indexOf
if (myImg.src.indexOf("like") > -1) { num1 = myImg.src.indexOf("like"); // indexOf 回传位置并转成数值 29 console.log(num1); myImg.src = "../../_image/find.png"; } else { myImg.src = "../../_image/like.png"; } }
8.insertBefore vs. appendChild
(1)insertBefore:指定在元素前增加 (插队)
(2)appendChild:直接在Html文件中增加元素 (从后面加上)
document.body.insertBefore(newElm, op06); document.body.appendChild(newImg);