js实现同时兼容pc和移动端的元素拖拽功能
时间: 2023-10-17 15:07:26 浏览: 71
要实现同时兼容 PC 端和移动端的元素拖拽功能,可以使用 HTML5 新增的 drag 事件和 touch 事件。
首先,需要将元素设置为可拖拽,可以使用 draggable 属性。例如:
```html
<div draggable="true">可拖拽的元素</div>
```
然后,需要监听元素的 dragstart、drag、dragend 事件或 touchstart、touchmove、touchend 事件来实现拖拽效果。
在 PC 端,可以使用 drag 事件来实现拖拽效果,例如:
```javascript
var dragElement = document.getElementById('drag-element');
dragElement.addEventListener('dragstart', function(event) {
// 拖拽开始时,保存拖拽元素的 ID
event.dataTransfer.setData('text/plain', event.target.id);
});
document.body.addEventListener('dragover', function(event) {
// 阻止默认拖拽行为
event.preventDefault();
});
document.body.addEventListener('drop', function(event) {
// 阻止默认拖拽行为
event.preventDefault();
// 获取拖拽元素的 ID
var id = event.dataTransfer.getData('text/plain');
var dragElement = document.getElementById(id);
// 将拖拽元素添加到放置区域
event.target.appendChild(dragElement);
});
```
在移动端,可以使用 touch 事件来实现拖拽效果,例如:
```javascript
var dragElement = document.getElementById('drag-element');
var startX, startY;
dragElement.addEventListener('touchstart', function(event) {
startX = event.touches[0].clientX;
startY = event.touches[0].clientY;
});
dragElement.addEventListener('touchmove', function(event) {
var offsetX = event.touches[0].clientX - startX;
var offsetY = event.touches[0].clientY - startY;
// 移动元素
this.style.transform = 'translate(' + offsetX + 'px, ' + offsetY + 'px)';
});
dragElement.addEventListener('touchend', function(event) {
// 拖拽结束时,清除 transform 样式
this.style.transform = '';
});
```
需要注意的是,移动端的 touch 事件可能会和浏览器默认行为冲突,需要使用 preventDefault() 方法来阻止默认行为。另外,由于移动端的屏幕尺寸多样化,需要根据具体情况来调整拖拽的逻辑和样式。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)