![](/img/trans.png)
[英]When I click on a canvas and drag my mouse, the cursor changes to a text-selection cursor. How can I prevent this?
[英]How can I prevent text/element selection with cursor drag
我做了一個分頁控件,我注意到點擊按鈕時很容易意外地選擇單個圖像和文本。 有可能阻止這種情況嗎?
澄清選擇我的意思是用鼠標突出顯示。 (嘗試將鼠標從屏幕的一側拖到另一側。)
如果您嘗試突出顯示此網格中的文本/控件,則無法選擇它。 怎么做的? 鏈接
拖動並選擇在鼠標按下事件上初始化並在隨后的鼠標移動時更新。 處理事件以開始拖動或跟隨鼠標時,取消事件的冒泡並覆蓋默認的瀏覽器返回:
你開始拖動mousedown和移動處理程序之類的東西 -
e=e || window.event; pauseEvent(e);
function pauseEvent(e){
if(e.stopPropagation) e.stopPropagation();
if(e.preventDefault) e.preventDefault();
e.cancelBubble=true;
e.returnValue=false;
return false;
}
對於拖動,您將捕獲mousedown
和mousemove
事件。 (並且希望touchstart
和touchmove
事件,以支持觸摸界面。)
您需要在down
和move
事件中調用event.preventDefault()
,以防止瀏覽器選擇文本。
例如(使用jQuery):
var mouseDown = false;
$(element).on('mousedown touchstart', function(event) {
event.preventDefault();
mouseDown = true;
});
$(element).on('mousemove touchmove', function(event) {
event.preventDefault();
if(mouseDown) {
// Do something here.
}
});
$(window.document).on('mouseup touchend', function(event) {
// Capture this event anywhere in the document, since the mouse may leave our element while mouse is down and then the 'up' event will not fire within the element.
mouseDown = false;
});
我想發表評論,但我沒有足夠的聲譽。 使用@kennebec建議的功能在我的javascript拖動庫中解決了我的問題。 它完美無瑕。
function pauseEvent(e){
if(e.stopPropagation) e.stopPropagation();
if(e.preventDefault) e.preventDefault();
e.cancelBubble=true;
e.returnValue=false;
return false;
}
我在我的mousedown和mousemove自定義函數中調用它,在我能識別出我點擊了正確的元素之后立即調用它。 如果我只是在函數的頂部調用它,我只是殺死文檔上的任何單擊。 我的函數在document.body上注冊為事件。
這是一篇非常古老的帖子。 它可能無法完全回答這種情況,但我使用CSS作為我的解決方案:
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
這可以通過在大多數瀏覽器中使用CSS和在IE中使用unselectable
expando來實現。 請在此處查看我的答案: 如何禁用使用CSS突出顯示文本?
試試這個:
document.onselectstart = function()
{
window.getSelection().removeAllRanges();
};
如下選擇,只需通過調用blur()函數來阻止它:
<input Value="test" onSelect="blur();">
如果你需要使用JavaScript阻止某個元素的文本選擇,那么對我來說最簡單的方法是分配userSelect樣式,如下所示:
var myElement = document.createElement('div');
myElement.style.userSelect = 'none';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.