所以我试图实现一个程序,根据用户的输入改变图像的宽度和高度,我可以正常实现,但我想用面向对象的编程来做,所以这是我的问题:我我需要在调用“material”函数时获取输入元素的值,但是如果我在函数内部移动输入元素,“sett”将无法正常工作,因为我在定义它们之前使用了输入元素,并且如果我将“设置”移动到我的代码的底部,那么“材料”的“调用者”参数将不起作用,因为在定义它之前我再次使用“设置”。 这是我的代码:
我也忘记删除html代码中的“top”和“left”输入元素,因此请考虑与它们相关的任何内容。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style>
#brazil {position:absolute;display:none;width:200;height:200;}
</style>
</head>
<body>
<input id="width" type="text" placeHolder="width"/>
<input id="height" type="text" placeHolder="height"/>
<input id="top" type="text" placeHolder="Vertical Position"/>
<input id="left" type="text" placeHolder="Horizontal Position"/>
<input type="button" value="Create" onclick="material(sett)"/>
<br>
<img id="brazil" src="brazil.png" alt="brazil"/>
<script>
var Cons = function(width,height) {
this.width = width;
this.height = height;
}
var brazil = document.getElementById("brazil");
var nwidth = document.getElementById("width").value;
var nheight = document.getElementById("height").value;
var sett = new Cons(nwidth,nheight);
var material = function(caller) {
brazil.style.width = caller.width;
brazil.style.height = caller.height;
brazil.style.display = "inline";
}
</script>
</body>
</html>
答案 0 :(得分:2)
你有不同的问题。最后我想你会这样:
var Cons = function(width, height) {
this.width = width + 'px';
this.height = height + 'px';
}
var material = function(caller) {
brazil.style.width = caller.width;
brazil.style.height = caller.height;
brazil.style.display = "inline";
}
var brazil = document.getElementById("brazil");
var nwidth = document.getElementById("width");
var nheight = document.getElementById("height");
var button = document.querySelector('input[type="button"]');
button.addEventListener('click', function(){
var sett = new Cons(nwidth.value, nheight.value);
material(sett);
});
我做了什么:
nheight
和nwidth`更改了逻辑,因此您不会缓存该值,但DOM元素+ 'px'
添加到类/对象,以便正确呈现PS。欢迎访问Portuguese Stackoverflow:)
答案 1 :(得分:0)
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style>
#brazil {position:absolute;display:none;width:200;height:200;}
</style>
</head>
<body>
<input id="width" type="text" placeHolder="width"/>
<input id="height" type="text" placeHolder="height"/>
<input id="top" type="text" placeHolder="Vertical Position"/>
<input id="left" type="text" placeHolder="Horizontal Position"/>
<input type="button" value="Create" onclick="material(sett())"/><br>
<img id="brazil" src="brazil.png" alt="brazil"/>
<script>
var Cons = function(width,height) {
this.width = width;
this.height = height;
};
var brazil = document.getElementById("brazil");
var sett = function(){
return new Cons(document.getElementById("width").value,document.getElementById("height").value)
};
var material = function(caller) {
brazil.style.width = caller.width;
brazil.style.height = caller.height;
brazil.style.display = "inline";
}
</script>
</body>
</html>
修改你的设置也应该有效!!!