这应该相当简单,但它不起作用,我没有看到它。我试图通过调用displayImage函数的onchange方法来改变我的图像。我缺少什么想法?
<html>
<head>
<title>Select Image</title>
<script type="text/javascript">
function displayImage() {
var image = document.getElementById("canvas");
var newImage = image.option[image.selectedIndex].value;
}
</script>
</head>
<body>
<form name="controls">
<img id="canvas" src="pictures/fire1.jpg" />
<select name="imageList" onchange="displayImage();">
<option value="pictures/fire1.jpg">Fire 1</option>
<option value="pictures/fire2.jpg">Fire 2</option>
<option value="pictures/fire3.jpg">Fire 3</option>
<option value="pictures/fire4.jpg">Fire 4</option>
</select>
</form>
</body>
</html>
答案 0 :(得分:1)
如果要根据下拉列表的值更改canvas元素的图像,请使用以下内容:
<html>
<head>
<title>Select Image</title>
<script type="text/javascript">
function displayImage(elem) {
var image = document.getElementById("canvas");
image.src = elem.value;
}
</script>
</head>
<body>
<form name="controls">
<img id="canvas" src="pictures/fire1.jpg" />
<select name="imageList" onchange="displayImage(this);">
<option value="pictures/fire1.jpg">Fire 1</option>
<option value="pictures/fire2.jpg">Fire 2</option>
<option value="pictures/fire3.jpg">Fire 3</option>
<option value="pictures/fire4.jpg">Fire 4</option>
</select>
</form>
</body>
</html>
将this
添加到函数调用中并修改函数本身。
答案 1 :(得分:1)
试试这个:
function displayImage() {
var image = document.getElementById("canvas"),
select = document.getElementsByTagName('select')[0];
image.src = select.value;
}
或更紧凑:
function displayImage() {
document.getElementById("canvas").src = document.getElementsByTagName('select')[0].value;
}
以下是example
答案 2 :(得分:0)
你可以试试这个:
将您的select
名称更改为id
。
<html>
<head>
<title>Select Image</title>
<script type="text/javascript">
function displayImage() {
var image = document.getElementById("imageList").value;
document.getElementsByTagName("img")[0].setAttribute("src",image)
}
</script>
</head>
<body>
<form name="controls">
<img id="canvas" src="pictures/fire1.jpg" />
<select id="imageList" onchange="displayImage();">
<option value="pictures/fire1.jpg">Fire 1</option>
<option value="pictures/fire2.jpg">Fire 2</option>
<option value="pictures/fire3.jpg">Fire 3</option>
<option value="pictures/fire4.jpg">Fire 4</option>
</select>
</form>
</body>
</html>