事件
.div1{ height: 1200px;width: 400px;background-color: #999; }
<form> <input type="text"> <input type="submit" value="确定"> </form> <div id="div1" class="div1">我是文本</div>
var oDiv = document.getElementById("div1"); var oForm = document.getElementsByTagName("form")[0]; var aInput = document.getElementsByTagName("input"); oForm.onsubmit = function(){console.log("submit");return false;} aInput[0].onfocus = function(){console.log("txtFocus");} aInput[0].onblur = function(){console.log("txtOnBlur");}//文本输入框失去焦点 aInput[0].onchange = function(){console.log("txtOnChange");}//文本输入框内容发生改变后,鼠标点击其他地方 aInput[0].oninput = function(){console.log("txtInput");}//文本框正在输入 oDiv.onclick = function(){console.log("click");}//onclick包括了onmousedown和onmouseup,click事件最后触发 oDiv.onmouseover = function(){console.log(this.innerText);} oDiv.onmousedown = function(){console.log("mousedown");} oDiv.onmouseup = function(){console.log("mouseup");} oDiv.onmousemove = function(){console.log("mousemove");}作用域中鼠标移动 oDiv.onmouseout = function(){console.log("mouseout");}
事件对象
当触发某个事件时,会产生一个事件对象,这个对象包含着所有有关事件的信息,包括事件的元素,类型,与特定的信息。通过事件绑定的执行函数可以得到一个隐藏参数,浏览器会自动分配这个EVENT参数;
e.clientX,e.clientY,当前鼠标距离页面左边距和顶部的距离,可视距离,忽略页面滚动条的存在
e.pageX,e.pageY,鼠标距离页面左边距和顶部的距离,绝对距离,如果页面有滚动条,
e.offsetX,e.offsetY 鼠标距离事件源的左边距和顶部的距离,只作用与该节点
oDiv.onclick = function(e){ console.log(e);//e隐藏参数,点击返回mouseEvent{istrusted:true,screenX:222,screenY:333,clientX:222,clientY:211,...}IE不支持,有局限性 console.log(window.event);//IE支持 var evt = e || event ;//封装隐藏参数, console.log(evt.clientX,evt.clientY); console.log(evt.pageX,evt.pageY); console.log(evt.offsetX,evt.offsetY); }
让一个元素SPAN实时显示鼠标在div中的当前鼠标距离页面左边距和顶部的距离
.div2{ position: relative;height: 200px;width: 300px;border: 1px solid #888 } .span{ position :absolute;bottom: 0 }
<div id="div2" class="div2"> <span class="span"></span> </div>
var oDiv2 = document.getElementById("div2"); var oSpan = oDiv2.children[0]; oDiv2.onmousemove = function(e){ var evt = e || event;//判断是否是IE浏览器还是其他浏览器的隐藏参数 oSpan.innerHTML = evt.clientX + "," + evt.clientY; } oDiv2.onmouseout = function(){ oSpan.innerHTML = null;//鼠标移出div的时候,清空span中的内容 }
键盘事件
document.onkeypress = function(){//按下字符键触发 console.log("onkeypress"); } document.onkeydown = function(){//按下任意键触发 console.log("onkeydown"); }
键盘事件altKey,ctrlKey,shiftKey判断
document.onkeydown = function(e){ var evt = e || event; console.log(evt.ctrlKey,evt.altKey,evt.shiftKey); console.log(evt.keyCode);//返回按下某个键的keyCode }
#div3{ height: 80px;width: 300px;border: 5px solid #888; }
var oDiv3 = document.getElementById("div3");
var aInput2 = document.getElementsByTagName("input");
aInput2[1].onclick = commentTxt;
function commentTxt(){
oDiv3.innerHTML += aInput2[0].value;
}
aInput2[0].onkeydown = function(e){
var evt = e || event;
if(evt.ctrlKey && evt.keyCode == 13){
commentTxt();
}
}