2016-04-19 51 views
1

這裏舉例:http://codepen.io/eliseosoto/pen/YqxQKx防止自動滾動的同時拖動通過滾動容器

const l = document.getElementById('scrollableList'); 
 
const item3 = document.getElementById('item3'); 
 

 
l.addEventListener('mouseover', function(e) { 
 
    e.stopPropagation(); 
 
    e.preventDefault(); 
 
    console.log('mouseover', e.target); 
 
}); 
 

 
item3.addEventListener('dragenter', function(e) { 
 
    e.stopPropagation(); 
 
    e.preventDefault(); 
 
    console.log('dragenter', e.target); 
 
}); 
 

 
l.addEventListener('dragover', function(e) { 
 
    console.log('xxx'); 
 
    e.stopPropagation(); 
 
    e.preventDefault(); 
 
}); 
 

 
l.addEventListener('scroll', function(e) { 
 
    console.log('scroll!', e); 
 
    e.stopPropagation(); 
 
    e.preventDefault(); 
 
}); 
 

 
item3.addEventListener('dragover', function(e) { 
 
    console.log('dragover item3'); 
 
    e.stopPropagation(); 
 
    e.preventDefault(); 
 
});
#container { 
 
    background-color: lightblue; 
 
} 
 

 
#scrollableList { 
 
    height: 50px; 
 
    background-color: green; 
 
    overflow: auto; 
 
}
<div id="container"> 
 
    <br> 
 
    <div id="scrollableList"> 
 
    <div>Item 1</div> 
 
    <div>Item 2</div> 
 
    <div id="item3">Item 3</div> 
 
    <div>Item 4</div> 
 
    <div>Item 5</div> 
 
    <div>Item 6</div> 
 
    <div>Item 7</div> 
 
    <div>Item 8</div> 
 
    <div>Item 9</div> 
 
    <div>Item 10</div> 
 
    <div>Item 11</div> 
 
    <div>Item 12</div> 
 
    <div>Item 13</div> 
 
    <div>Item 14</div> 
 
    </div> 
 
    <br> 
 
    <div id="dragMe" draggable="true">Drag me near the top/bottom of the Item list.</div> 
 
</div>

注意,當你拖動「拖動我。」文附近的項目的頂部/底部列表中,它將自動滾動的列表。

通常,這種行爲很有用,因爲您可以放入所需的放置區域,但有時根本不需要。

有沒有一種純JS方式在Chrome 47+中禁用該行爲?我試着用'dragover','mouseover','scroll'等不同的元素來無效。

回答

0

我能夠通過存儲滾動的當前位置和滾動事件發生時完成此操作,我將scrollTop設置爲先前存儲的位置。

const list = document.getElementById('scrollableList'); 
const dragMe = document.getElementById('dragMe'); 

var scrollPosition = 0; 

dragMe.addEventListener('dragstart', function(e) { 
    scrollPosition = list.scrollTop; 
    list.addEventListener('scroll', preventDrag); 
}); 

dragMe.addEventListener('dragend', function(e) { 
    list.removeEventListener('scroll', preventDrag); 
}); 

function preventDrag(e) { 
    list.scrollTop = scrollPosition; 
}; 

這很奇怪,你不能取消滾動事件。

http://codepen.io/cgatian/pen/JXZjOB?editors=1010

+0

看起來像這個問題在這裏回答。 http://stackoverflow.com/q/4770025/684869 – cgatian

+0

謝謝!然而,這仍然不完美,但它有一些缺點:a)您需要將dragstart/dragend偵聽器添加到任何可以拖到列表上的任何東西。 b)您仍然可以通過拖動文件或通過從列表中選擇並拖動文本來滾動列表。 –