JavaScript自学笔记 第7次
1.onload和onunload是打开与关闭页面事件,可以用来出cookie。
<!DOCTYPE html> <html> <body onload="checkCookies()"> //打开body页面的时候触发函数
<script> function checkCookies() { if (navigator.cookieEnabled==true) //检查cookie并弹窗提示 { alert("已启用 cookie") } else { alert("未启用 cookie") } } </script>
<p>提示框会告诉你,浏览器是否已启用 cookie。</p> </body> </html> |
2.onchange是在改变时触发。
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script> function myFunction() { var x=document.getElementById("fname"); x.value=x.value.toUpperCase(); //toUpperCase大写转换 } </script> </head> <body>
请输入英文字符:<input type="text" id="fname" onchange="myFunction()"> <p>当您离开输入字段时,会触发将输入文本转换为大写的函数。</p>
</body> </html> |
3.onmouseover和onmouseout,鼠标移入和移除时触发。
<!DOCTYPE html> <html> <body>
<!-- this表示当前元素,所以在Function里就不必使用getElementById来获取元素了。--> <div onmouseover="mOver(this)" onmouseout="mOut(this)" style="background-color:green;width:120px;height:20px;padding:40px;color:#ffffff;">把鼠标移到上面</div>
<script> function mOver(obj) { obj.innerHTML="谢谢" }
function mOut(obj) { obj.innerHTML="把鼠标移到上面" } </script>
</body> </html> |
4.onmousedown鼠标按下,onmouseup鼠标弹起,onclick鼠标点击。
<!DOCTYPE html> <html> <body>
<div onmousedown="mDown(this)" onmouseup="mUp(this)" style="background-color:green;color:#ffffff;width:90px;height:20px;padding:40px;font-size:12px;">请点击这里</div> <br> <div onClick="mClick(this)" style="background-color:green;color:#ffffff;width:90px;height:20px;padding:40px;font-size:12px;">用onClick来触发函数,实现变色</div> <script> function mDown(obj) { obj.style.backgroundColor="#1ec5e5"; obj.innerHTML="请释放鼠标按钮"; }
function mUp(obj) { obj.style.backgroundColor="green"; obj.innerHTML="请按下鼠标按钮"; } //用onClick来实现变色,第1次学习的灯泡就是用这个onclick来触发实现。 function mClick(obj) { if (obj.style.backgroundColor.match("green")) { obj.style.backgroundColor="red"; obj.innerHTML="用onClick来触发函数,实现变色"; } else { obj.style.backgroundColor="green"; obj.innerHTML="用onClick来触发函数,实现变色"; } } </script>
</body> </html> |