首页 > 解决方案 > 如何使 HTML 按钮引用外部 javascript 文件中的操作?

问题描述

我对编码非常陌生(第 1 周),请原谅任何滥用术语,我仍在学习。

在我的作业中,我有一个按钮,单击该按钮需要更改屏幕上框的大小。我相信我正确编写了 javascript,但我不知道如何告诉 HTML 文件中的按钮“当我单击按钮时,请查看 javascript 文件中的操作”HTML 中按钮操作的代码是什么.

我正在使用 VScode。

<!DOCTYPE html>
<html>
<head>
    <title>Jiggle Into JavaScript</title>
</head>
<body>
    <p>Press the buttons to change the box!</p>

   <div id="box" style="height:150px; width:150px; background- color:orange; margin:25px"></div>

    <button id="growBtn">Grow</button>
    <button id="blueBtn">Blue</button>
    <button id="fadeBtn">Fade</button>  
    <button id="resetBtn">Reset</button>

    <script type="text/javascript" src="javascript.js"></script>

</body>
</html>
document.getElementById("growBtn").addEventListener("click", function(){document.getElementById("box").style.height="250px"});

document.getElementById("blueBtn").addEventListener("click", function(){document.getElementById("box").backgroundColor = blue });

document.getElementById("fadeBtn").addEventListener("click", function(){document.getElementById("box").backgroundColor= lightorange });

document.getElementById("resetBtn").addEventListener("click", function(){document.getElementById("box").style.height = "150px"})

当我单击 HTML 文件中的按钮时,它应该调用 javascript 文件并执行操作(更改大小、颜色等)。

标签: javascripthtml

解决方案


您缺少以下style属性:

document.getElementById("box").style.backgroundColor = "lightorange";

并且您在 div 样式属性之间有一个空格,background-color这会破坏样式:

style="height:150px; width:150px; background-color:orange; margin:25px"

推荐阅读