使用Javascript更改HTML图像大小

时间:2016-12-04 23:18:56

标签: javascript html image styling

所以我正在尝试创建一个用于更改图像大小的选择菜单,但我不知道这段代码有什么问题或者如何修复它。

HTML:

<img id="dogpicture" src="dog1.png" alt="dog" height="150" width="150"></img>

<select id="dogsize" name="sizeofdog" onchange="dogsize(this.value);">
    <option value="small"> small </option>
    <option value="default" selected> default </option>
    <option value="big"> big </option>
</select>

JS:

function dogsize(option){
    if (option == "small"){
        document.getElementById('dogpicture').height = "50";
        document.getElementById('dogpicture').width = "50";
    }
    if (option == "default"){
        document.getElementById('dogpicture').height = "100";
        document.getElementById('dogpicture').width = "100";
    }
    if (option == "big"){
        document.getElementById('dogpicture').height = "150";
        document.getElementById('dogpicture').width = "150";
    }
}

1 个答案:

答案 0 :(得分:0)

似乎工作正常。我做的唯一更改是将img标记修复为void标记(并且我包含了狗图片的链接)。

您正在直接更改元素height/width,但您也可以更改样式属性height/width

如果有其他代码影响图像或下拉列表,那么也需要查看它。

&#13;
&#13;
// original function
function dogsize(option){
    if (option == "small"){
        document.getElementById('dogpicture').height = 50; // string "50" also works
        document.getElementById('dogpicture').width = 50;
    }
    if (option == "default"){
        document.getElementById('dogpicture').height = 100;
        document.getElementById('dogpicture').width = 100;
    }
    if (option == "big"){
        document.getElementById('dogpicture').height = 150;
        document.getElementById('dogpicture').width = 150;
    }
}

// alternate syntax that changes the style attribute properties
function dogsizeStyleMutation(option){
    if (option == "small"){
        document.getElementById('dogpicture').style.height = "50px";
        document.getElementById('dogpicture').style.width = "50px";
    }
    if (option == "default"){
        document.getElementById('dogpicture').style.height = "100px";
        document.getElementById('dogpicture').style.width = "100px";
    }
    if (option == "big"){
        document.getElementById('dogpicture').style.height = "150px";
        document.getElementById('dogpicture').style.width = "150px";
    }
}
&#13;
<img id="dogpicture" src="https://www.what-dog.net/Images/faces2/scroll0015.jpg" alt="dog" height="150" width="150" />

<br/>
<h3>Changes element height/width</h3>

<select id="dogsize" name="sizeofdog" onchange="dogsize(this.value);">
    <option value="small"> small </option>
    <option value="default" selected> default </option>
    <option value="big"> big </option>
</select>

<br/>
<h3>Changes element style attr height/width</h3>

<select id="dogsizeStyle" name="sizeofdogInStyle" onchange="dogsizeStyleMutation(this.value);">
    <option value="small"> small </option>
    <option value="default" selected> default </option>
    <option value="big"> big </option>
</select>
&#13;
&#13;
&#13;