javascript事件的响应方式

来源:互联网 发布:aws s3 php 上传 编辑:程序博客网 时间:2024/06/06 02:10

1 通过元素内的事件响应

如:<html>
<head>
<style type="text/css">
</style>
<script type="text/javascript">
function changeBg()
{
document.getElementById("text").style.backgroundColor="pink";
}

function restore()
{
document.getElementById("text").style.backgroundColor="white";
}
</script>
</head>
<body>
<input type="text" id="text" onfocus="changeBg()" onblur="restore()"/>
</body>
</html>

2 先获得元素再将它与事件绑定

例子如下:

<html>
<head>
<style type="text/css">
</style>
</head>
<body>
<input type="text" id="text" />
<script type="text/javascript">
 var text=document.getElementById("text");
 text.onclick=function()
 {
  this.style.backgroundColor="pink";
 }

  text.onblur=function()
  {
  this.style.backgroundColor="white";
  }
</script>
</body>
</html>

3通过增加监听的方式来:

<html>
<head>
<style type="text/css">
</style>
</head>
<body>
<input type="text" id="text" />
<script type="text/javascript">
 var text=document.getElementById("text");
 if(!text.attachEvent)
 {
  text.addEventListener("click",change,false);  //非IE不打支持on打头
  text.addEventListener("blur",restore,false);
  //removeEventListener(event,function,capture/bubble); 监听的移除
 }
  else
  {
  text.attachEvent("onclick",change);       //ie支持只on打头
  text.attachEvent("onblur",restore);
  //detachEvent(event,function);            监听的移除
  }
 function change()
 {
  text.style.backgroundColor="pink";
 }

 function restore()
  {
  text.style.backgroundColor="white";
  }
</script>
</body>
</html>


0 0
原创粉丝点击