我想将javascript代码与html页面分开并将其放入单独的javascript文档中,但是当我这样做时,代码不再起作用了。附:我确实在html页面中指定从单独的javascript文档中检索代码。
<script type="text/javascript">
function updateTextInput() {
var valueHue = document.getElementById('sliderHue').value;
var valueSaturation = document.getElementById('sliderSaturation').value;
var valueLightness = document.getElementById('sliderLightness').value;
document.getElementById('textHue').value = valueHue;
document.getElementById('textSaturation').value = valueSaturation + "%";
document.getElementById('textLightness').value = valueLightness + "%";
var color = "hsl(" + valueHue + ", " + valueSaturation + "%, " + valueLightness + "%)";
document.getElementById('colorDisplay').setAttribute('style', "background-color:" + color);
}
</script>
<div>
Hue:
<br>
<input id="sliderHue" type="range" min="0" max="360" step="1" onchange="updateTextInput();">
<br>
<input type="text" id="textHue" value="">
<br>
<br>
<br>Saturation:
<br>
<input id="sliderSaturation" type="range" min="0" max="100" step="1" onchange="updateTextInput();">
<br>
<input type="text" id="textSaturation" value="">
<br>
<br>
<br>Lightness:
<br>
<input id="sliderLightness" type="range" min="0" max="100" step="1" onchange="updateTextInput();">
<br>
<input type="text" id="textLightness" value="">
</div>
答案 0 :(得分:0)
这可能是因为你订购它的方式。如果你把它放在你引用的元素之前,它就不会起作用。有一些解决方案,最简单的可能是将脚本移动到文档的末尾,更简洁的方法是下载jQuery并将代码包装在。
中。$(function(){ /* Code goes here */ }
答案 1 :(得分:0)
这里的html页面如下
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
<script type="text/javascript" src="ds.js"></script>
</head>
<body>
<div>
Hue:
<br>
<input id="sliderHue" type="range" min="0" max="360" step="1" onchange="updateTextInput();">
<br>
<input type="text" id="textHue" value="">
<br>
<br>
<br>Saturation:
<br>
<input id="sliderSaturation" type="range" min="0" max="100" step="1" onchange="updateTextInput();">
<br>
<input type="text" id="textSaturation" value="">
<br>
<br>
<br>Lightness:
<br>
<input id="sliderLightness" type="range" min="0" max="100" step="1" onchange="updateTextInput();">
<br>
<input type="text" id="textLightness" value="">
</div>
</body>
</html>
和 ds.js
function updateTextInput() {
var valueHue = document.getElementById('sliderHue').value;
var valueSaturation = document.getElementById('sliderSaturation').value;
var valueLightness = document.getElementById('sliderLightness').value;
document.getElementById('textHue').value = valueHue;
document.getElementById('textSaturation').value = valueSaturation + "%";
document.getElementById('textLightness').value = valueLightness + "%";
var color = "hsl(" + valueHue + ", " + valueSaturation + "%, " + valueLightness + "%)";
document.getElementById('colorDisplay').setAttribute('style', "background-color:" + color);
}
你会得到你的输出