我使用js创建一个“复制到剪贴板”按钮,使用来自这里的以下代码:
function copy(selector){
var $temp = $("");
$("body").append($temp);
$temp.attr("contenteditable", true)
.html($(selector).html()).select()
.on("focus", function() { document.execCommand('selectAll',false,null); })
.focus();
document.execCommand("copy");
$temp.remove();
}然后使用以下方法加载脚本:add_action( 'wp_enqueue_scripts', 'load_copy' );
function load_copy() {
wp_enqueue_script('copyjs', get_template_directory_uri() . '/js/copy.js', array('jquery') );
}然后,我有一个按钮设置来触发这个js onclick,从div元素中复制文本。这个函数工作得很好,除了:因为js是在WP中的脚注中加载的,所以当触发onclick事件时,focus()命令会导致页面滚动到底部。我尝试过使用focus({preventScroll: true}),但是这个函数不起作用,而且我对js不太了解原因。有人有办法阻止页面滚动吗?编辑:添加我现在使用的解决方案,从下面Veerji的答案中提取,只需做一个修改。function copyToClipboard(selector){
var $temp = jQuery("");
jQuery("body").append($temp);
$temp.attr("contenteditable", true)
.html(jQuery(selector).html()).css('position', 'fixed').select()
.on("focus", function() { document.execCommand('selectAll',false,null); })
.focus().css('position', 'static');
document.execCommand("copy");
$temp.remove();
}
发布于 2020-12-11 21:54:02
在jQuery focus
中,默认情况下,将页面滚动到元素。如果我们使用focus({preventScroll: true})
,我们的复制功能将不能像您一样工作。所以我用了一些css黑客。请参见下面的jQuery代码。
function copyToClipboard(selector, event){
event.preventDefault();
var $temp = jQuery("");
jQuery("body").append($temp);
$temp.attr("contenteditable", true)
.html(jQuery(selector).html()).css('position', 'fixed').select()
.on("focus", function() { document.execCommand('selectAll',false,null); })
.focus().css('position', 'static');
document.execCommand("copy");
$temp.remove();
}这对我来说很好。如果您不想使用这个黑客,也可以使用一些纯javascript代码。例如,这
https://wordpress.stackexchange.com/questions/379707
复制相似问题