我遇到setAttribute()的问题。我搜索了互联网和这个网站,但他们没有解决我的问题。我想用javascript更改图片的宽度和高度,但它不起作用。请帮帮我。
<html>
<head>
<meta charset="utf-8"/>
<title>Width Height Changer</title>
<script type="text/javascript">
function chang(){
var wid = document.getElementById('width').value;
var hei = document.getElementById('height').value;
var set = document.getElementById('pic');
if(Number(wid) && Number(hei)){
set.setAttribute("style","width : wid");
set.setAttribute("style","height : hei");
}else{
alert('Error');
}
}
</script>
</head>
<body>
<input type="text" id="width" placeholder="Enter Width"/>
<input type="text" id="height" placeholder="Enter Height"/>
<button onclick="chang()">OK</button><br/>
<img src="back4.jpg" id="pic" />
</body>
答案 0 :(得分:1)
更好用:
set.style.width = wid +"px";
set.style.height =hei+"px";
function chang(){
var wid = document.getElementById('width').value;
var hei = document.getElementById('height').value;
var set = document.getElementById('pic');
if(Number(wid) && Number(hei)){
set.style.width = wid +"px";
set.style.height =hei+"px";
}else{
alert('Error');
}
}
答案 1 :(得分:0)
您的变量被引用为字符串,因为它们被引用 - 更改为:
if(Number(wid) && Number(hei)){
set.setAttribute("style","width :" + wid + "px");
set.setAttribute("style","height :" + hei + "px");
} else {
答案 2 :(得分:0)
你可以使用:
set.style.width = wid + "px";
set.style.height = hei + "px";
或
set.style.setAttribute("width", wid + "px");
set.style.setAttribute("height",hei + "px");
答案 3 :(得分:0)
建议进行一些更改以提高可读性。使用id =&#34;宽度&#34;和&#34;身高&#34;令人困惑,因为宽度/高度也是JS / html关键字。另外一些额外的错误检查永远不会伤害:
function chang(){
var wid = document.getElementById('inputWidth').value;
var hei = document.getElementById('inputHeight').value;
var set = document.getElementById('pic');
if(Number(wid) && Number(hei) && set && set.style){
set.style.setAttribute("width", wid + "px");
set.style.setAttribute("height",hei + "px");
}else{
alert('Error');
}
}