我的目标是将图像复制到剪贴板。鉴于出于安全原因不允许复制图像,我要解决的用例是:
- 用户按下复制按钮
- 通过jquery选择图像(焦点并选择)
- 提示用户按
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>
关于javascript - jquery 选择图像不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36363606/