当您将鼠标悬停在Trello中的卡片上并按Ctrl + C时,该卡片的URL被复制到剪贴板。他们怎么做到的?

据我所知,没有涉及Flash电影。我已经安装了Flashblock,并且Firefox的“网络”标签显示未加载Flash电影。 (这是通常的方法,例如,ZeroClipboard。)

他们如何实现这种魔力?

(目前,我想我顿悟了:您无法在页面上选择文本,因此我认为它们具有不可见的元素,它们通过JavaScript代码创建文本选择,而Ctrl + C触发浏览器的默认行为,即复制该不可见节点的文本值。)

最佳答案

披露: I wrote the code that Trello uses;下面的代码是Trello用于完成剪贴板技巧的实际源代码。

我们实际上并没有“访问用户的剪贴板”,而是通过在用户按Ctrl + C时选择一些有用的东西来帮助用户。
听起来您已经解决了;我们利用了这样一个事实,当您想按Ctrl + C时,必须先按Ctrl键。当按下Ctrl键时,我们会在一个文本区域中弹出一个文本区域,该文本区域包含我们要在剪贴板上结束的文本,并选择其中的所有文本,因此当按下C键时,所有选择都已设置。 (然后,当出现Ctrl键时,我们将隐藏文本区域。)
具体来说,Trello这样做:

TrelloClipboard = new class
  constructor: ->
    @value = ""

    $(document).keydown (e) =>
      # Only do this if there's something to be put on the clipboard, and it
      # looks like they're starting a copy shortcut
      if !@value || !(e.ctrlKey || e.metaKey)
        return

      if $(e.target).is("input:visible,textarea:visible")
        return

      # Abort if it looks like they've selected some text (maybe they're trying
      # to copy out a bit of the description or something)
      if window.getSelection?()?.toString()
        return

      if document.selection?.createRange().text
        return

      _.defer =>
        $clipboardContainer = $("#clipboard-container")
        $clipboardContainer.empty().show()
        $("<textarea id='clipboard'></textarea>")
        .val(@value)
        .appendTo($clipboardContainer)
        .focus()
        .select()

    $(document).keyup (e) ->
      if $(e.target).is("#clipboard")
        $("#clipboard-container").empty().hide()

  set: (@value) ->
在DOM中,我们有:
<div id="clipboard-container"><textarea id="clipboard"></textarea></div>
剪贴板内容的CSS:
#clipboard-container {
  position: fixed;
  left: 0px;
  top: 0px;
  width: 0px;
  height: 0px;
  z-index: 100;
  display: none;
  opacity: 0;
}
#clipboard {
  width: 1px;
  height: 1px;
  padding: 0px;
}
...,而CSS做到了这一点,所以当它弹出时,您实际上看不到textarea,但是它是“可见的”足以复制的区域。
当您将鼠标悬停在卡片上时,它会调用
TrelloClipboard.set(cardUrl)
...因此,剪贴板助手会在按下Ctrl键时知道要选择的内容。

关于javascript - Trello如何访问用户的剪贴板?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17527870/

10-11 22:36
查看更多