jquery选择图像不起作用

jquery select image not working

本文关键字:不起作用 图像 选择 jquery      更新时间:2023-11-14

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

  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>

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

我使用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>

$(document).ready(function(){
    $("#myImage").bind('load', function(){
        $("#myImage").focus();
        $("#myImage").select();
        alert("ok");
    });
});

您还应该检查以下内容:图像加载时的jQuery回调(即使在缓存图像时)