記事詳細


投稿日
2025年09月01日18時39分
タイトル

コピーボタンでコピー可能にする

内容

 //Details.cshtmlのhtmlCodeの抜粋

<dd class="col-sm-10">

          <div style="border: 2px solid black; padding: 10px;">  //「コピーする」ボタンを作成:表示

         <div style="text-align: right;">

             <button onclick="copyToClipboard()">コピーする</button>

         </div>

                  <px  id="htmlCode">@Html.Raw(Model.Content)</px>

       @*   <textarea class="preformatted-text" id="htmlCode" style="field-sizing:content;">@Html.DisplayFor(model => model.Content)</textarea> *@

     </div>

 </dd>

//Details.cshtmlのhtml 同ページのJava <script>

<script>

    function copyToClipboard() {

      const text = document.getElementById("htmlCode").innerText;  //idが”htmlCode”というオブジェクトの中身をtext変数に代入

      // textarea.select();

      // textarea.setSelectionRange(0, 99999); // モバイル対応

      // document.execCommand("copy");

      // alert("コードがコピーされました!");

      navigator.clipboard.writeText(text).then(() => {   //Clipboadにtextをコピーする

        alert('テキストをコピーしました: ' + text);

      }).catch(err => {

        alert('コピーに失敗しました: ' + err);

      });

    }

</script>

<style>

    textarea {

        width: 100%;

        height: 150px;

        margin-bottom: 10px;

            background-color: antiquewhite;

    }

    button {    //buttonのスタイルを定義

        padding: 10px 20px;

        background-color: #4CAF50;

        color: white;

        border: none;

        cursor: pointer;

    }


        button:hover {

            background-color: #45a049;

        }

    </style>


Powered by Froala Editor

添付画像

Current Image
Genreのカテゴリ-名
MVCTutorials
編集 | 記事一覧