js的事件

来源:互联网 发布:简述算法的复杂度分析 编辑:程序博客网 时间:2024/05/01 01:18

概述 : js是采用事件驱动的机制来响应用户操作的,也就是说当用户对某个html元素进行某个操作时,

会产生一个事件,该事件会驱动某些函数来处理。

案例:  
<script type="text/javascript">  

//事件处理函数 

function test1(event)

{   window.alert("ok");  

window.alert(event.clientX);  }  
</script>  
<input type="button" value="tesing" onclick="test1(event)"/>


事件源: 就是产生事件的地方(html元素)

事件: 点击/鼠标移动/键按下..
事件对象: 当某个事件发生时,可能会产生一个事件对象,这个事件对象会封装该事件的信息(比如点击的x,y. keycode),

传递给事件处理程序

事件处理程序: 响应用户的事件.

案例

<html> <head>  
<script type="text/javascript"> 

function show_coords(event)


x=event.clientX; y=event.clientY;
alert(event+"X coords: " + x + ", Y coords: " + y)

}  
</script>  </head>  
<!--body元素响应onmousedown事件 -->

<body onmousedown="show_coords(event)">  
<p>Click in the document. An alert box will alert the x and y coordinates of the mouse pointer.</p> 

</body>  </html> 


事件的分类
① 鼠标事件

② 键盘事件

③ html事件

④ 其它事件

例1

<html> <head>  
<script type="text/javascript">   

function showkey(event)

{  

if(event.keyCode==65)

{    window.alert("a被按下");

   }

else if(event.keyCode==66)

{    window.alert("b被按下");   }

}
</script>  </head>  
<!--body元素响应onmousedown事件 -->

<body onkeydown="showkey(event)">   
</body>  </html>

例2

function mychange(val)

{   var div1=document.getElementById("div1");  

   if(val.value=='red')

   {    //通过js获取div这个对象       

        //window.alert(div1.style.width);   

        div1.style.backgroundColor="red";   }

        else if(val.value=="black")

        {    //通过js获取div这个对象       

             //window.alert(div1.style.width);   

             div1.style.backgroundColor="black";

      }

  }

function sayHello()

{   window.alert("red按钮被按下");  }   
</script>  </head>   
<body>   

<div id="div1" style="width:400px;height:300px;background-color:red"> 

</div> 

<input type="button" value="red" onclick="mychange(this),sayHello()"/> 

<input type="button" value="black" onclick="mychange(this)"/>  
</body> 

不同的浏览器事件种类不一样
如何区分当前浏览器的内核是什么?(区分出ie6/7/8/  火狐等)
代码如下:  
<script language="javascript">     

if(window.XMLHttpRequest)     

{ //Mozilla, Safari, IE7,IE8   
        if(!window.ActiveXObject)      


   // Mozilla, Safari,             

   alert('Mozilla, Safari');

         }
Else {   
           alert('IE7 .8');

         }

      }
else  {   
      alert('IE6');     } 

</script>


案例:防止用户通过点击鼠标右键菜单拷贝网页内容
 <script type="text/javascript">    

function test()

{  

//window.alert("没有菜单");  

return false;


function test2()

{   //window.alert("全选不行"); 

return false;  }   
</script> 
</head>  
<!--body元素响应onmousedown事件 -->
<body oncontextmenu="return test();" onselectstart="return test2();">

我的内容!是大幅度

</body>


让弹出窗口变小:
<script type="text/javascript">  

window.resizeTo(300,200);

</script>

0 0
原创粉丝点击