2014-11-21 82 views
0

請幫助執行以下問題。 需要對特定元素執行單擊操作,但需要使用偏移量。點擊元素(帶偏移量)

如果我使用一個標準的點擊 - element.click(),然後單擊發生在元素的左上角:

[image #1]

但我需要做的請點擊這裏:

[image #2]

我可以執行元素上點擊+偏移? 類似的東西 -

element.click().offset('top: 32, left: 32') 

p.s. Ssory爲我的英語。

回答

0

這是做到這一點的最好辦法:

function func(){ 
 
alert("Circle clicked!") 
 
}
div{ 
 
    border-radius: 100000px; 
 
    width: 100px; 
 
    height: 100px; 
 
    background-color: red; 
 
    cursor: pointer; 
 
}
<div onClick="func()"></div>

0
  • 我你使用element.click()和假設你使用jQuery看到。你想要的不是jQuery的可能,它不能爲事件設置偏移參數,你必須使用原生的javascript。
  • 點擊事件對象在裏面有兩對參數:clientX/clientY和。兩者都描述點擊發生時鼠標指針的位置。
  • 相對於文檔,位置是,而不是元素。標準點擊具有clientX: 0, clientY: 0,因此它出現在文檔的左上角,而不是元素的左上角。
  • 如果要單擊某個元素,則必須將clientX/clientY設置爲元素相對於文檔的位置。您可以通過.getBoundingClientRect()查找元素位置。
  • Rect .left/.top中的位置是元素topLeft拐角處的座標。在事件中使用它們點擊其左上角。
  • 現在您可以向座標添加偏移量。在Rect裏面你還可以找到元素的width/height。如果將它們中的一半添加到x, y,則會獲得元素中心的座標。在事件中使用它會在其中心點擊一下。

function clickOnElem(elem, offsetX, offsetY) { 
    var rect = elem.getBoundingClientRect(), 
     posX = rect.left, posY = rect.top; // get elems coordinates 
    // calculate position of click 
    if (typeof offsetX == 'number') posX += offsetX; 
    else if (offsetX == 'center') { 
     posX += rect.width/2; 
     if (offsetY == null) posY += rect.height/2; 
    } 
    if (typeof offsetY == 'number') posY += offsetY; 
    // create event-object with calculated position 
    var evt = new MouseEvent('click', {bubbles: true, clientX: posX, clientY: posY});  
    elem.dispatchEvent(evt); // trigger the event on elem 
} 

您按如下方式使用它;

var el = document.getElementById("myElem"); 
clickOnElem(el); // clicks on topLeft corner 
clickOnElem(el, 'center'); // clicks on elements center 
clickOnElem(el, 30, 40); // clicks inside element, 30px from left and 40px from top