繁体   English   中英

如何在 html 中为 Javascript 添加 onclick 事件 - 非程序员

[英]How to add an onclick event in html for Javascript - by a non programmer

这是我的第一篇文章,我正在寻求帮助。 我不是任何类型的程序员,但热衷于理解编程并设置了一个Codepen 页面作为示例。 我正在尝试与一些询问该页面是否允许鼠标点击工作的人分享?

我想要得到的是在没有键盘点击事件的情况下使它工作,即onkeydown=onkeyup= ,这是现在发生的事情,但是通过鼠标点击工作,这将允许它在手机浏览器中工作?

如果有人可以编写/显示我需要的代码,我将不胜感激。 我看到 HTML 需要定义onclick事件,然后做两件事,第一件事是speakPrevious ,第二件事是getNewRandomColor 我认为 JavaScript 需要定义onclick元素? 但我不确定...

  `HTML`
  <body onkeydown="speakPrevious()">
  <body onkeyup="getNewRandomColor()">
  

  `JS`
  speakPrevious();
  function speakPrevious() {
     var synth = window.speechSynthesis;
     var utterThis = new SpeechSynthesisUtterance(window.value);
     synth.speak(utterThis);
  }

    getNewRandomColor();
    function getNewRandomColor() {
    var myArray = ['Red','Green', 'Blue',  'Yellow', ];
    var rand = myArray[Math.floor(Math.random() * myArray.length)];     

    document.getElementsByTagName("body")[0].style.backgroundColor = rand;
    var oldRand = rand;
    window.value = oldRand;
   }

如果您使用事件侦听器,您可以允许用户使用键盘或通过单击页面与 web 页面进行交互。 在您的 javascript 中,您可以添加代码(如下所示),只要单击 html 主体元素,该代码就会触发 function 代码。 这将添加允许用户单击页面的功能。

const page = document.querySelector("body");
    page.addEventListener("click", function () {
        speakPrevious();
        getNewRandomColor();
    });

此外,您可能会发现将 body 标签事件合并到一个包含两个事件的 body 标签中会更容易。

<body onkeydown="speakPrevious()" onkeyup="getNewRandomColor()">

这将允许用户单击页面以触发功能或使用键盘事件。

我的最终文档代码如下所示

<html>
<body onkeydown="speakPrevious()" onkeyup="getNewRandomColor()">
    <p>The algorithm will select colors at random from RGBY and you may see the same color several times in a row. This
        is expected behavior and NOT a fault.<br>Click inside the color and press any keyboard key to move to the next
        color.</p>
</body>
<script>
    const page = document.querySelector("body");
    page.addEventListener("click", function () {
        speakPrevious();
        getNewRandomColor();
    });

    function speakPrevious() {
        var synth = window.speechSynthesis;
        var utterThis = new SpeechSynthesisUtterance(window.value);
        synth.speak(utterThis);
    }

    function getNewRandomColor() {
        var myArray = ['Red', 'Green', 'Blue', 'Yellow', ];
        var rand = myArray[Math.floor(Math.random() * myArray.length)];

        document.getElementsByTagName("body")[0].style.backgroundColor = rand;
        var oldRand = rand;
        window.value = oldRand;
    }
</script>
</html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM