我有一个带有图像、按钮和文本框的表单。单击按钮时,我可以将图像的高度和宽度调整为文本框中输入的内容。单击按钮时我的图像就会消失。
这是我的代码
<!DOCTYPE HTML>
<html>
<head>
<title>Resize Image</title>
</head>
<body>
<script>
function resizeimage()
{
var theImg = document.getElementById('image');
theImg.height = size;
theImg.width = size;
}
var size=parseInt(document.getElementById('txtbox'));
</script>
<form name ="ResizeImage">
<img src = "cookie.jpg" id="image">
</br>
<input type=button value="Resize" onclick="resizeimage()">
</br>
<input type=text id="txtbox"
</form>
</body>
</html>
最佳答案
除了 HTML 问题(请通过验证器运行)之外,主要问题是读取图像大小的代码部分位于函数之外。页面加载时,会发生这种情况。
- 函数
resizeimage()
已定义 - var
size
设置为此时输入中的任何内容 - 页面内容已加载。
在 2. 处,输入甚至还不存在,因为 3. 尚未完成,因此 var size
设置为 undefined
。此后它永远不会改变,因为函数 resizeimage()
不会再次尝试读取图像的大小。
此外,document.getElementById
返回一个元素。您必须使用其 .value
属性来读取用户放入其中的内容
试试这个:
function resizeimage()
{
var size=parseInt(document.getElementById('txtbox').value);
var theImg = document.getElementById('image');
theImg.height = size;
theImg.width = size;
}
关于javascript - 根据文本框中输入的数据调整图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19158457/