js事件

来源:互联网 发布:mac拷不进移动硬盘 编辑:程序博客网 时间:2024/06/05 16:25
  1. onclick事件;
  2. onmousemove事件;
  3. onkeydown事件;
    事件实例:
    onclick事件:
    函数效果:在window窗口上随意点击获取x y的值;
    函数思路:
    1:思路很简单就是一个点击事件,然后获相应xy值,但是有一点需要注意的就是兼容问题;
    知识点:
    1:event.clientX,获取window中x轴上的值;
    2:event.clientY,获取window中x轴上的值;
    函数内容:
 document.onclick=function(e){      var oEvent=e||event;      //event是兼容IE,e是兼容google       alert('x:'+event.clientX+'y:'+event.clientY);   }

注意:这里需要注意的就是兼容问题event是兼容IE,e是兼容google
这里写图片描述

onmousemove事件:
函数效果:window上的div随着鼠标的移动而移动,
函数思路:
1:首先建立一个div;
2: 给div一个绝对定位;
3:onmousemove事件;
4:注意事项;

<script>  var obox=document.getElementById('box')  document.onmousemove=function(e){      oevent= e||event      //event是兼容IE,e是兼容google;      console.log('x:'+oevent.clientX+'y:'+oevent.clientY);      obox.style.left=oevent.clientX+ 'px';      obox.style.top=oevent.clientY +'px';    }</script>

注意事项:注意:这里需要注意的就是兼容问题event是兼容IE,e是兼容google
onkeydown事件:
知识点:keyCode,键盘对应的数字;
函数的效果: 点击键盘的上下左右键,window页面上的div块上下左右移动;
函数思路:
1:首先要获取上下左右键的键值,
2:做判断;
3:根据判断的方向,获取div的style.top、style.left 、offsetLeft、offsetTop值。
4:给出一个speed值。让div按照这个速度移动,如果是向左移动则,oBox.style.left=oBox.offsetLeft-speed+’px’;
5: 需要注意的事项,一个是兼容问题还有一个是当div移动到左上边缘时接着按方向键,div会超出window界面。移动到右下边缘时会出现滚动条;

var obox=document.getElementById('box')  document.onkeydown=function(e){   // alert(e.keyCode)   //down 40 top 38 left 37 right 39;  if (e.keyCode==37) {    obox.style.left=obox.offsetLeft-10+ 'px'  }  if (e.keyCode==39) {    obox.style.left=obox.offsetLeft+10+ 'px'  }  if (e.keyCode==40) {    obox.style.top=obox.offsetTop+10+ 'px'  }  if (e.keyCode==38) {    obox.style.top=obox.offsetTop-10+ 'px'  }  }</script>

注意事项:这里处理注意事项只写下思路,当时上和左边时,我一左边为例,首先判断obox.offsetLeft是否小于零如果小于零obox.style.left=0;下边和右边时首先要获取window的height和width这里以右边为例,如果obox.offsetLeft-oBox.width>window.width时这时obox.style.left=obox.offsetLeft-oBox.width;

原创粉丝点击