我正在努力将javascript功能添加到具有多个按钮的基本HTML页面。当我在外部JS文件中包含一个函数时,代码可以工作,但当我尝试添加另一个按钮功能时,代码停止工作。
如何解决此问题?
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Jiggle Into JavaScript</title>
<!-- <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> -->
</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="button1">Grow</button>
<button id="button2">Blue</button>
<button id="button3">Fade</button>
<button id="button4">Reset</button>
<script type="text/javascript" src="javascript.js"></script>
</body>
</html>
段:
document.getElementById("button1").addEventListener("click", function(){
document.getElementById("box").style.height = "500px";
});
document.getElementById("button2").addEventListener("click", function(){
document.getElementById("box").style.background-color = "blue";
});
<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="button1">Grow</button>
<button id="button2">Blue</button>
<button id="button3">Fade</button>
<button id="button4">Reset</button>
答案 0 :(得分:6)
这里的语法不正确:
document.getElementById("box").style.background-color = "blue";
-
是减法运算符,它不能用作属性文字的一部分。通过将CSS名称转换为camelCase来创建样式属性,因此它应该是:
document.getElementById("box").style.backgroundColor = "blue";
答案 1 :(得分:0)
您还可以使用简单的background
document.getElementById("box").style.background = "blue";
答案 2 :(得分:0)
由于您也标记了JQuery
,因此这里是JQuery版本。在JQuery中,您可以使用css()
添加/更改多个CSS属性:
$("#button1").on('click', function() {
$("#box").css({
'height': '500px'
});
})
$("#button2").on('click', function() {
$("#box").css({
'background-color': 'blue'
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Jiggle Into JavaScript</title>
<!-- <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> -->
</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="button1">Grow</button>
<button id="button2">Blue</button>
<button id="button3">Fade</button>
<button id="button4">Reset</button>
<script type="text/javascript" src="javascript.js"></script>
</body>
</html>
答案 3 :(得分:0)
如果你想要一个JQuery答案,这里也是一个。
$('button').click(function() {
var $box = $('#box');
if($(this).attr('id') == 'button1')
{
$box.css('height','500px');
}
else if ($(this).attr('id') == 'button2')
{
$box.css('background-color', 'blue');
}
});