2016-02-24 28 views
0

我想在鼠標下方更改子元素的索引,但不會中斷點擊事件。這可能嗎?當事件mousedownmouseup事件發生在一個和相同的元件被處理是否可以在不中斷點擊事件的情況下重新排序子女onodouown

<script> 

function mouseDownHandler(event) { 
    var p = event.currentTarget.parentNode; 
    p.appendChild(event.currentTarget); 

} 
</script> 

<div style="position: absolute; left: 50px; top: 100px; width: 50px; height: 100px; background-color: red;" onmousedown="mouseDownHandler(event)" onclick="console.log('click 1')">This is a test</div> 


<div style="position: absolute; left: 70px; top: 100px; width: 50px; height: 100px; background-color: blue;" onmousedown="mouseDownHandler(event)" onclick="console.log('click')">This is a test</div> 

https://jsfiddle.net/9d2dvcqj/

+0

這是怎麼斷的單擊事件? –

+0

如果appendChild更改元素的索引,則不會觸發click事件。 (即使mouseDown和mouseUp仍然在目標上) –

回答

1

Click事件。因此,當元素的順序發生變化時 - 它不會發生,並且不會調用事件click

一個解決方案 - 要記住哪個元素是mousedown事件並將其與事件mouseup發生比較:

function mouseDownHandler(event) { 
    var p = event.currentTarget.parentNode; 
    mouseDownHandler.mde = event.currentTarget; 
    p.appendChild(event.currentTarget); 
} 

function mouseUpHandler(event) { 
    if (event.currentTarget === mouseDownHandler.mde) { 
    document.body.innerHTML += 'click<br/>'; 
    } else { 
    mouseDownHandler.mde = null; 
    } 
} 

https://jsfiddle.net/nrd98ujr/

+0

我傾向於類似的解決方法。這似乎是要走的路,但我想知道是否有一種可能重新排序的方式,不會導致mousedown/mouseup序列中斷。 –

相關問題