2015-10-23 63 views
9

我在表格中有一些數據,點擊它可以在其他地方導航,但人們要求能夠突出顯示文本以便能夠將文本複製/粘貼到別處。由於它們是鏈接,因此HTML中的默認行爲是拖動鏈接...我不知道爲什麼或如何有用,但我想在某些鏈接上禁用該鏈接。阻止鏈接拖動,但仍允許文本突出顯示

TL; DR:我希望能夠以高亮顯示鏈接拖不動它的文本。

下面的gif應該有助於解釋我的問題。

Example

以下方法我想要的東西:

我所看到的例子是同時防止突出&使用這樣的事情

<a draggable="false" href="#">

或拖動這

.no-drag { 
    user-drag: none; 
} 

或者這

myElement.ondragstart = function() { 
    return false; 
}; 

但很明顯,這是不是我所需要here.Is什麼,我想可能這樣做?

回答

3

@Julien Grégoire's answer above把我在正確的軌道此,但下面的代碼是什麼,我最終使用的基本知識。

var clickedEl = document.getElementById("test"); 
 
var limit = 5; 
 
var mouseMoved = false; 
 

 
function resetEvents() { 
 
    clickedEl.onmousemove = null; 
 
    clickedEl.ondragstart = null; 
 
    clickedEl.onmouseleave = null; 
 
    mouseMoved = false; 
 
} 
 

 
clickedEl.onmousedown = function (downEvent) { 
 
    if (clickedEl.attributes.href) { 
 
     clickedEl.onclick = function (clickEvent) { 
 
      if (mouseMoved) { 
 
       clickEvent.preventDefault(); 
 
      } 
 
      resetEvents(); 
 
     }; 
 
    } 
 
    
 
    clickedEl.onmouseleave = function() { 
 
     resetEvents(); 
 
    }; 
 

 
    clickedEl.onmousemove = function (moveEvent) { 
 
     // This prevents the text selection being dragged 
 
     clickedEl.ondragstart = function (dragEvent) { 
 
      dragEvent.preventDefault(); 
 
     }; 
 

 
     if (Math.abs(moveEvent.x - downEvent.x) >= limit || Math.abs(moveEvent.y - downEvent.y) >= limit) { 
 
      // If user clicks then moves the mouse within a certain limit, select the text inside 
 
      window.getSelection().selectAllChildren(clickedEl); 
 
      mouseMoved = true; 
 
     } 
 
    }; 
 

 
};
<a id="test" href="http://stackoverflow.com">Click or select</a>

1

您可以檢測用戶是否在點擊後移動鼠標,如果是這樣,使用window.getSelection管理選擇。事情是這樣的,例如:

var linkEl = document.getElementById('test') 
 

 
linkEl.onmousedown = function(downEvent) { 
 

 
    var clickedEl = downEvent.target; 
 
    var mouseMoved = false; 
 

 
    clickedEl.onmousemove = function() { 
 

 
    // If user clicks then moves, select the whole link 
 
    window.getSelection().selectAllChildren(clickedEl); 
 

 
    // Set a flag to prevent opening the link 
 
    mouseMoved = true; 
 

 
    // Reset mousemove, else it'll run constantly 
 
    clickedEl.onmousemove = null; 
 

 
    // This is only to prevent having the text selection being dragged 
 
    clickedEl.ondragstart = function(dragEvent) { 
 
     dragEvent.preventDefault(); 
 
    } 
 
    } 
 

 
    if (mouseMoved) { 
 
    // If mouse has moved, prevent default 
 
    downEvent.preventDefault(); 
 
    } 
 
}
<a draggable="false" id="test" href="http://stackoverflow.com">Click or select</a>

+0

這個偉大的工程,但它似乎總是突出顯示文本,無論如果我點擊或移動鼠標 –