0
0

【練習】ブラウザで作った文字列コピーツール

Last updated at Posted at 2024-05-25

JavaScriptで簡単なツールを作る練習

ボタンを押すとクリップボードに文字列がコピーされるツールです。
文字列を選択してからコピーする、を繰り返す時に便利なツールです。

<!doctype html>
<html lang="ja">
	<head>
		<meta charset="utf-8">
		<title>copyToClipBoard</title>
	</head>
	<style>
		section{
			width: 500px;
			margin: 10px;
			padding: 10px;
			color: #333;
			background-color: #ddd;
			border-radius: 10px;
		}
		p{
			margin: 5px;
		}
		h2{
			margin: 0;
		}
		.search{
			width: 50px;
			padding: 2.5px 5px;
			color: blue;
			border: solid 1px #fff;
			border-radius: 10px;
		}
		.replace{
			width: 50px;
			padding: 2.5px 5px;
			color: green;
			border: solid 1px #fff;
			border-radius: 10px;
		}
	</style>
	<body>
		<h1></h1>
		<section>
			<h2 class="search">検索</h2>
			<article>
				<h3>条件</h3>
				<p class="copyString">A|B|C</p>
				<button class="copyButton">Copy</button>
			</article>
		</section>
		<section>
			<h2 class="replace">置換</h2>
			<article>
				<h3>置換前</h3>
				<p class="copyString">\s*\*\s*/\s*$</p>
				<button class="copyButton">Copy</button>
			</article>
			<article>
				<h3>置換後</h3>
				<p class="copyString"></p>
				<button class="copyButton">Copy</button>
			</article>
		</section>
		<script>
			function copyToClipBoard(){
				const sections = document.querySelectorAll(`section`);
				for(const section of sections){
					const articles = document.querySelectorAll(`article`);
					for(const article of articles){
						const copyString = article.getElementsByClassName(`copyString`)[0];
						const copyButton = article.getElementsByClassName(`copyButton`)[0];
						copyButton.addEventListener(`click`, () => {
							navigator.clipboard.writeText(copyString.innerHTML);
						});
					}
				}
			}
			
			copyToClipBoard();
		</script>
	</body>
</html>

見た目

image.png

改良した方が良いところ

  • ボタンを押すと「コピーされました」というチップを表示したい。
  • むしろマクロ化した方が速い。
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0