一键复制产品信息到剪贴板
在页面上点击按钮,把部分商品信息复制到剪贴板,可以任意粘贴到需要的地方。主要用到的方法为:setSelectionRange()方法;document.execCommand("copy")
<div><p>产品名称:<span class="js-p-title">XXXXXXXXXXXXXXXXXXXXXXXXX</span></p><p>产品英文名称:<span class="js-en-title">eeeeeeeeeeeee</span></p><p>产品数量:<span class="js-cunt">eeeeeeeeeeeee</span></p><p>型号:<span class="size_span">W1</span><span class="size_span">W2</span><span class="size_span">W3</span></p><p>价格:<span class="price_span">10元</span><span class="price_span">20元</span><span class="price_span">30元</span></p></div><div style="text-align: center;"><input id="copy_text_a" type="button" value="一键复制" onclick="copytext()" style="margin-top: 30px; background-color: #2ebac0; color: #fff; width: 150px; height: 50px; border: 0 none; border-radius: 5px;"/><br><!-- 赋值给textarea --><textarea id="copytext" style="display:none" ></textarea></div>
function copytext(){$('#copytext').show();var msg="产品名称: "+$('.js-p-title').text().trim();msg=msg+"\r\n英文名称: "+$(".js-en-title").text().trim();msg=msg+"\r\n产品数量: "+$(".js-cunt").text().trim();let size = [], price = []$.each($('.size_span'), (index,item)=>{size.push($('.size_span').eq(index).text().trim())price.push($('.price_span').eq(index).text().trim())});msg=msg+"\r\n产品规格: "+size.join('/');msg=msg+"\r\n产品价格: "+price.join('/');msg=msg+"\r\n产品链接: "+window.location.href;//$('#copytext').val(msg);$('#copytext').select();$('#copytext')[0].setSelectionRange(0,msg.length);document.execCommand("copy");$('#copytext').hide();$('#copy_text_a').val("复制成功");setTimeout(function () {$('#copy_text_a').val("一键复制产品信息");}, 3000);}