【问题标题】:jquery select image not workingjquery选择图像不起作用
【发布时间】:2016-07-21 16:33:18
【问题描述】:

我的目标是将图像复制到剪贴板。由于安全原因不允许复制图像,我要解决的用例是:

  1. 用户按下复制按钮
  2. 通过jquery选择图片(聚焦并选择)
  3. 提示用户按ctrl + c复制图片

问题是,如果我为输入执行此操作,我可以轻松选择其中的文本,但我无法为图像执行此操作。下面是我正在尝试做的抽象版本,现在主要只是选择图像。

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#myImage").focus();
    $("#myImage").select();
});
</script>
</head>
<body>
 <img id="myImage" width="220" height="277" src="https://pixabay.com/static/uploads/photo/2015/10/01/21/39/background-image-967820_960_720.jpg" alt="The Scream">
</body>
</html>

以下是相同的示例,但对于输入,它可以工作。

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#myInput").focus();
    $("#myInput").select();
});
</script>
</head>
<body>
 
<input id="myInput" value="hello"/>
</body>
</html>

如果有人能给我正确的方法,我将不胜感激。谢谢。

【问题讨论】:

标签: javascript jquery html


【解决方案1】:
$(document).ready(function(){
    $("#myImage").bind('load', function(){
        $("#myImage").focus();
        $("#myImage").select();
        alert("ok");
    });
});

您还应该检查一下:jQuery callback on image load (even when the image is cached)

【讨论】:

    【解决方案2】:

    我使用clipboard.js 解决了我的问题,并找到了一种只需一个按钮即可将图像复制到剪贴板的方法。以下是我的解决方案。

    请注意,在您下载 cliboardjs 之前它不会工作。

    <!DOCTYPE html>
    <html>
    <head>
      <script src="clipboard.min.js"></script>
      <title></title>
    </head>
    <body>
    
      <div id="myDiv">
    
        <img width="220" height="277" src="https://pixabay.com/static/uploads/photo/2015/10/01/21/39/background-image-967820_960_720.jpg" alt="The Scream">
    
      </div>
      <button class="btn" data-clipboard-target="#myDiv">
        Copy to clipboard
      </button>
      <script type="text/javascript">
    
        var clipboard = new Clipboard('.btn');
    
        clipboard.on('success', function(e) {
          e.clearSelection();
        });
    
      </script>
    </body>
    </html>

    【讨论】:

      猜你喜欢
      • 2010-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-16
      • 1970-01-01
      • 2012-01-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多