根据文本框中输入的数据调整图像大小

Resize an image from data entered in a textbox

本文关键字:调整 数据 图像 输入 文本      更新时间:2023-09-26

具有图像、按钮和文本框的表单。 我 在单击按钮时将图像的高度和宽度调整为文本框中输入的大小。单击按钮时,我的图像会消失。

这是我的代码

<!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问题(请通过验证器运行它)之外,主要问题是读取图像大小的代码部分在函数之外。在页面加载时,就会发生这种情况。

  1. 定义resizeimage()函数
  2. var size设置为此时输入中的任何内容
  3. 将加载页面的内容。

在 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;
}

工作示例:http://jsfiddle.net/KZH5p/

我会先缓存ids:

var input = document.getElementById('txtbox');
var theImg = document.getElementById('image');
function resizeimage() {
  var size = input.value;
  theImg.height = size;
  theImg.width = size;
}

function changeDogsSize() {
    var dogSize = parseInt((id_input).value);
    id_dog.width = dogSize;
}
<!doctype html>
<html lang="en">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
        integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <link rel="stylesheet" href="styles.css">
</head>
<body>
     <div class="container bg-light mt-3"></div>
     <!--changing dogs image-->
     <div class="container">
         <img id="id_dog" src="https://i.pinimg.com/originals/e4/9d/75/e49d755afcd02cdbf39d374b42a10ecd.jpg"  alt="dog">
         <input id="id_input" type="text" class="form-control mt-4" id="exampleInputAmount" placeholder="enter img width">
         <button id="id_changeBtn" onclick="changeDogsSize()" type="button" class="btn btn-secondary btn-lg mt-3 text-dark">Change</button>
     </div>
</body>
</html>