如何复制子字符串从URL复制到剪贴板框?



我正试图为我的项目制作一个复制到剪贴板的网页。我从Codepen得到这个代码。我试着按照自己的想法去做,对JavaScript的理解不够,我做不到。我正试图得到这些全部:-

1。从URL中获取子字符串。

2。通过点击复制按钮从框中复制子字符串。

我使用下面给出的代码来复制URL。

https://oauth2.example.com/code=abcd.。

是完整的URL。但是我想只复制code=**abcd**在我的复制到剪贴板框。

index . html

<div class="container">
<div class="label">
Authorization Code
</div>
<div class="copy-text">
<input type="text" class="text" value="code" />
<button><i class="fa fa-clone"></i></button>
</div>
</div>

index.js

let copyText = document.querySelector(".copy-text");
copyText.querySelector("button").addEventListener("click", function () {
let input = copyText.querySelector("input.text");
input.select();
document.execCommand("copy");
copyText.classList.add("active");
window.getSelection().removeAllRanges();
setTimeout(function () {
copyText.classList.remove("active");
}, 2500);
});

style.css

* {
margin: 0px;
padding: 0px;
box-sizing: border-box;
}
body {
font-family: "Roboto", sans-serif;
background: #f0f2f7;
}
.container {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.label {
padding: 10px;
font-size: 18px;
color: #111;
}
.copy-text {
position: relative;
padding: 10px;
background: #fff;
border: 1px solid #ddd;
border-radius: 10px;
display: flex;
}
.copy-text input.text {
padding: 10px;
font-size: 18px;
color: #555;
border: none;
outline: none;
}
.copy-text button {
padding: 10px;
background: #5784f5;
color: #fff;
font-size: 18px;
border: none;
outline: none;
border-radius: 10px;
cursor: pointer;
}
.copy-text button:active {
background: #809ce2;
}
.copy-text button:before {
content: "Copied";
position: absolute;
top: -45px;
right: 0px;
background: #5c81dc;
padding: 8px 10px;
border-radius: 20px;
font-size: 15px;
display: none;
}
.copy-text button:after {
content: "";
position: absolute;
top: -20px;
right: 25px;
width: 10px;
height: 10px;
background: #5c81dc;
transform: rotate(45deg);
display: none;
}
.copy-text.active button:before,
.copy-text.active button:after {
display: block;
}
footer {
position: fixed;
height: 50px;
width: 100%;
left: 0;
bottom: 0;
background-color: #5784f5;
color: white;
text-align: center;
}
footer p {
margin: revert;
padding: revert;
}

得到url查询字符串

const queryString = window.location.search;

获取代码参数值

const urlParams = new URLSearchParams(queryString);
const code = urlParams.get('code');

保存代码参数到剪贴板

navigator.clipboard.writeText(code);

相关内容

  • 没有找到相关文章