day51—JavaScript綁定事件

轉換學開發,代碼100天——2018-05-06javascript

今天學習JavaScript的綁定事件。由於瀏覽器的緣由綁定事件須要考慮兼容性問題。css

attachEvent     IE瀏覽器 ,ie9以上事件執行順序與綁定順序相同;ie9如下事件執行順序與綁定順序相反          

btn.attachEvent("onclick",function(){
   alert("a");
});html

     
detachEvent

btn.detachEvernt("onclick",function(){
   alert("a");
});java

addEventListener FF及chrome瀏覽器

btn.addEventListener("click",function(){
     alert("a");
});chrome

removeEventListener

btn.renoveEventListener("onclick",function(){
   alert("a");
});瀏覽器

 

如對一個按鈕添加多個事件:app

 

<script type="text/javascript">
        window.onload = function(){
            var btn = document.getElementById("btn");
            addMyEvent(btn,"click",function()
            {
                alert("a");
            });
            addMyEvent(btn,"click",function()
            {
                alert("b");
            });
        }

        function addMyEvent(obj,ev,fn){
            if (obj.attachEvent) {
                obj.attachEvent("on"+ev,fn);
            }
            else{
                obj.addEventListener(ev,fn);
            }
        }
    </script>

 補充:將上一篇文章中的拖拽事件改爲線框拖拽效果學習

按下鼠標,拖動物體時:this

鬆開鼠標後:spa

<!DOCTYPE html>
<html>
<head>
    <title>javascript 拖拽</title>
    <style type="text/css">
    #div1{
        width: 100px;
        height: 100px;
        background: red;
        position: absolute;
    }
    .Box{
        border: 1px dashed black;
        position: absolute;
    }
</style>

<script type="text/javascript"> window.onload = function(){ var oDiv = document.getElementById("div1"); var disX =0; var disY =0; oDiv.onmousedown = function(ev){ //建立虛線框 var oBox = document.createElement("div"); oBox.className = "Box"; oBox.style.width = oDiv.offsetWidth+"px"; oBox.style.height = oDiv.offsetHeight+"px"; oBox.style.left = oDiv.offsetLeft+"px"; oBox.style.top = oDiv.offsetTop+"px"; document.body.appendChild(oBox); var oEvent = ev||event; disX = oEvent.clientX-oDiv.offsetLeft; disY = oEvent.clientY-oDiv.offsetTop; if (oDiv.setCapture) { //鼠標移動事件 oDiv.onmousemove = mouseMove; oDiv.onmouseup = mouseUp; oDiv.setCapture();//ie專用 return false; }else{ //鼠標移動 document.onmousemove =mouseMove; document.onmouseup = mouseUp; return false; } //鼠標按下事件 function mouseMove(ev){ var oEvent = ev||event; var l = oEvent.clientX-disX; var t = oEvent.clientY-disY; oBox.style.left = l+"px"; oBox.style.top = t+"px"; }; //鼠標擡起事件 function mouseUp() { this.onmousemove = null; this.onmouseup = null; if (this.setCapture) { this.releaseCapture();//ie專用 } oDiv.style.left = oBox.offsetLeft+"px"; oDiv.style.top = oBox.offsetTop+"px"; document.body.removeChild(oBox); }; }; } </script>
    </head>
    <body>
        <div id="div1"></div>
    </body>
    </html>
相關文章
相關標籤/搜索