如何在html和javascript中连接一个id到触发函数

问题描述 投票:0回答:1

通过下面的代码,我试图让它对静音和静音的输入做出反应。因此,当在文本框中输入静音或静音时,它将改变颜色为红色的muteon和绿色的mute,在这种情况下,id="text "和 "text1"。谢谢

HTML.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET.NET:

  <!DOCTYPE html>
    <html>
    <body>

    <p>Write something in the text field to trigger a function.</p>

    <input type="text" id="myInput" oninput="myFunction()">

    <p id="demo"></p>

    <script>
    function myFunction() {
      var x = document.getElementById("myInput").value;
      document.getElementById("demo").innerHTML = "You wrote: " + x;
    }
    </script>

    </body>
    </html>

想要链接的HTML。

<h1 class="l1-txt1 txt-center p-t-0 p-b-10">
    <p id="text1" style="color:white; font-weight: 600"></p>
</h1>

<h1 class="l1-txt1 txt-center p-t-0 p-b-60">
    <p id="text" style="color:crimson; font-weight: 600"></p>
</h1>
javascript html css telnet
1个回答
2
投票

你可以试试下面的方法。

function myFunction() {
  var x = document.getElementById("myInput").value;
  var t1 = document.getElementById("text1");
  var t2 = document.getElementById("text");
  document.getElementById("demo").innerHTML = "You wrote: " + x;
  if(x.trim().toLowerCase() == 'mute'){
    t1.style.color = 'green';
    t2.style.color = 'green';
  }
  else if(x.trim().toLowerCase() == 'muteon'){
    t1.style.color = 'red';
    t2.style.color = 'red';
  }
}
<p>Write something in the text field to trigger a function.</p>

<input type="text" id="myInput" oninput="myFunction()">

<p id="demo"></p>
<h1 class="l1-txt1 txt-center p-t-0 p-b-10">
  <p id="text1" style="color:white; font-weight: 600">Text 1</p>
</h1>

<h1 class="l1-txt1 txt-center p-t-0 p-b-60">
  <p id="text" style="color:crimson; font-weight: 600">Text</p>
</h1>
© www.soinside.com 2019 - 2024. All rights reserved.