繁体   English   中英

使用html5 draggable属性时,保留拖动A元素的外观

[英]Preserve appearance of dragged A element when using html5 draggable attribute

使用'draggable'html5属性时,如何保留拖动的A元素的外观。 在某些浏览器(Safari和Chrome)上拖动锚点时,拖动的帮助器将被替换为拖动元素的浏览器本机实现,如屏幕截图所示:

拖动DIV时

拖动DIV时

拖动A时

拖动A时

HTML

<div class="draggable">Draggable DIV</div>
<a href="" class="draggable">Draggable A</a>

CSS

$('.draggable').attr('draggable', true);

这是我组装的快速JSBin来演示这个问题http://jsbin.com/pihayeceza/1/edit

谢谢

我可以使用DataTransfer.setDragImage保留拖动元素的外观。 如果我将以下代码添加到jsbin实例中的JavaScript中,它适用于Firefox,Chrome和Safari:

$('a.draggable').on('dragstart', function (ev) {
  var dt = ev.originalEvent.dataTransfer;
  // In IE browsers, setDragImage does not exist. However, the issue we are 
  // trying to fix does not happen in these broswers. So if setDragImage is not
  // available, then just don't do anything.
  if (dt.setDragImage) 
    dt.setDragImage(ev.target, 0, 0);

});

事件的dataTransfer字段具有与拖动操作关联的DataTransfer对象。 您必须从原始DOM事件而不是从jQ​​uery事件包装器中获取它,因此ev.originalEvent.dataTransfer

对于IE浏览器, setDragImage不存在,但问题中报告的问题不会出现在第一位,所以如果没有setDragImage ,我们就不会调用它。

带有更新代码的bin

发生此问题是因为拖动具有href属性的链接的默认行为是创建包含要用作拖动占位符的URL的图像。 您可以通过删除href属性来解决此问题,但是,为了解决这个问题而不必删除href属性,您可以使用mousedown / up事件处理程序删除属性,然后重新添加它,使锚点可单击*。

 $('.draggable').attr('draggable', true).on('mousedown', function () { if ($(this).is('a')) { $(this).data('href', this.href); $(this).removeAttr('href'); } }).on('mouseup', function () { if ($(this).is('a')) { $(this).attr('href', $(this).data('href')); } }).on('click', function () { console.log(this.href); }); 
 .draggable { margin: 10px; display: block; width: 200px; background: #fafafa; color: #333; text-decoration: none; height: 40px; border: 1px solid #eaeaea; line-height: 40px; text-align: center; cursor: move; border-radius: 20px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="draggable">Draggable DIV</div> <a href="http://www.google.com" target="_blank" class="draggable">Draggable A</a> 

*注意:堆栈片段不允许您关注该链接。

用div包裹你的锚标签,并在锚标签上设置draggable =“false”。

<div class="draggable">
    <a href="" draggable="false">Draggable A</a>
</div>

您将需要额外的样式,以防止按钮/链接看起来是蓝色和下划线。

.draggable a {
  color: inherit;
  text-decoration: inherit;
}

在这里修改了你的jsbin http://jsbin.com/rebayif/edit

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM