JavaScript学习摘录(一)

来源:互联网 发布:countdown软件 怎么用 编辑:程序博客网 时间:2024/05/29 12:31

在HTML中查找元素,通过类名查找在IE5、6、7、8无效


通过id和标签查找元素

假设页面中有两个标签p和h1,id都是a

var x=document.getElementById("a");var y=x.getElementsByTagName("p");
通过上边两行可以查到找id为a的p标签

修改HTML内容

document.getElementById("p1").innerHTML="New text!";

修改HTML图片

document.getElementById("image").src="image.jpg";

修改HTML元素的样式:颜色

document.getElementById("p1").style.color="red";

点击时改变元素样式

<h1 id="id1">My Heading 1</h1><button type="button" onclick="document.getElementById('p1').style.color='red'">点击变红色</button>

显示和隐藏元素

<p id="p1">这是一段文本。</p><input type="button" value="隐藏文本" onclick="document.getElementById('p1').style.visibility='hidden'" /><input type="button" value="显示文本" onclick="document.getElementById('p1').style.visibility='visible'" />

事件-->点击时

<p onclick="this.innerHTML='变了吧'">点击变字</p> //this 是指当前的标签
事件-->点击时,调用函数

<script>function changeText(id){id.innerHTML="变了吧";}</script><p onclick="changeText(this)">点击变字</p>

使用JS向HTML分配事件

<button type="button" id="btn">BTN</button><script>function displayDate(){document.getElementById("p1").innerHTML=Date();}//使用 JavaScript 来向 HTML 元素分配事件document.getElementById("btn").onclick=function(){displayDate()};</script>


onload和onunload事件

onload可以在页面启动时来检测用户浏览器的类型、版本等信息,根据这些信息我们在代码中做适配处理等,贴一个学习看的例子

<!DOCTYPE html><html><body onload="checkCookies()"><script>function checkCookies(){if (navigator.cookieEnabled==true){alert("已启用 cookie")}else{alert("未启用 cookie")}}</script><p>提示框会告诉你,浏览器是否已启用 cookie。</p></body></html>

onchange事件

通俗来说就是监听变化的,假设一个输入框在里边的文本发生变化时(用户在输入时长短肯定会变的)来执行函数,像什么长度不够啊,长度太长啊,输入不合法啊,都可以在用户边输边提示

<!--当鼠标焦点转移时,输入的字母都变大写--><script type="text/javascript">function changeTxt(id){id.value=id.value.toUpperCase();}</script><input type="text" id="t1" onchange="changeTxt(this)"/>


鼠标移动事件  onmouserover和onmouseout 

<!--鼠标移入,移出--><script>function moveIn(id){id.innerHTML="移入";}function moveOut(id){id.innerHTML="移出";}</script><p onmouseover="moveIn(this)" onmouseout="moveOut(this)"> 鼠标移动上来试试 </p>

更多事件请查看w3school,点击跳转






原创粉丝点击