事件的类型:
(1)鼠标事件:
click用户点击鼠标时发生,当用户的焦点在按钮上,并按了回车键,同样会触发这个事件
dbclick 用户双击鼠标左键时发生 mouseover 鼠标移出某个元素到另一个元素身上发生
mouseout鼠标指针在某个元素上,且用户正要将其移除元素的边界时发生
mousedown用户点击任意一个按钮时发生
mouseup用户松开任意一个按钮时发生
contextmenu 弹出右键菜单。
<p>Use your mouse to click and double click the red square</p> <div style="width:100px; height:100px; "
onmouseover="handleEvent(event)"
onmouseout="handleEvent(event)"
onmousedown="handleEvent(event)"
onmouseup="handleEvent(event)"
onclick="handleEvent(event)"
ondblclick="handleEvent(event)"
id="div1"></div>
<p><textarea id="txt1" rows="15" cols="50"></textarea></p>
//onmousemove、onmouseout改变图片外观的流行方法
<img src="1.jpg" onmousemove="this.src=‘2.jpg‘" onmouseout="this.src=‘1.jpg‘" />
//获取鼠标的位置
<script>
var getCoordInDocument = function(e){
e = e || window.event;
var x = e.pageX || (e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft));
var y = e.pageY ||(e.clientY + (document.documentElement.scrollTop || documwent.body.scrollTop));
return {‘x‘:x,‘y‘:y};
}
<script>
mouseover,mousemove,mouseout没有什么好说,并且无浏览器差异。我们来看鼠标滚轮事件,这个差异很严重。IE、Safari、 Opera 、chrome是mousewheel事件,Firefox是DOMMouseScroll事件。事件属性方面,IE等是event.detail,Firefox是event. wheelDelta。IE等往上滚一圈为120,往下滚一圈为-120。Firefox往上滚一圈为-3,往下滚一圈为3。我们可以构造一个函数来削除它们的差异。
var mouseScroll = function(fn){
var roll = function(){
var delta = 0,
e = arguments[0] || window.event;
delta = (e.wheelDelta)?e.wheelDelta / 120 : -(e.detail || 0) / 3;
fn(delta); //回调函数中的回调函数
}
if(window.netscape){
document.addEventListener(‘DOMMouseScroll‘,roll,false);
}else{
document.onmousewheel = roll;
}
}
此函数接受一函数作为参数,如:
mouseScroll(function(delta){
var obj = document.getElementById(‘scroll‘),
current = parseInt(obj.offsetTop)+(delta*10);
obj.style.top = current+"px";
});
实例检测:请用鼠标滚轮移动方块
<script type="text/javascript">
var $ = function(id){ return document.getElementById(id)}
window.onload = function(){
mouseScroll(function(delta){
var obj = $(‘scroll‘),
current = parseInt(obj.offsetTop)+(delta*10);
obj.style.top = current+"px"; });
}
var mouseScroll = function(fn){
var roll = function(){
var delta = 0,
e = arguments[0] || window.event;
delta = (e.wheelDelta) ? e.wheelDelta / 120 : -(e.detail || 0) / 3;
fn(delta);//回调函数中的回调函数
} if(window.netscape ){
document.addEventListener(‘DOMMouseScroll‘, roll, false);
}
else{
document.onmousewheel = roll;
} }
</script>
<style title="text/css">
#scroll {
color:#fff;
background:#369;
width:70px;
height:70px;
position:absolute;
left:500px;
top:200px;
}
</style>
<body>
<div id="scroll">请用鼠标滚轮移动方块</div>
</body>
(1)键盘事件: