JavaScript Image(如何设置高度和宽度,使用document.getElementById()。src ='')

时间:2017-05-02 17:59:23

标签: javascript

如何将布什图片设置为100px×100px?

<!DOCTYE html>
<html>
    <head>
        <title> Title </title>
        <script>

        </script>
    </head>

    <body>
        <button type = button onclick = "document.getElementById('myImage').src='bush.jpg'">Bush</button>
        <button type = button onclick = "document.getElementById('myImage').src='obama.jpg'">Obama</button>
        <p>Default is Obama </p>
        <img id = "myImage" src = "obama.jpg" style = "width: 100px;  height: 100px">
    </body>
</html>

我正处于学习javascript的开始阶段。不确定真正需要什么其他信息。我只是想在全栈式Web开发中找到一份工作,并意识到我在学校学到的东西(Java / C / C ++)的工作量减少了。我知道这是一个相对简单的问题,但不知道如何谷歌答案,因为我不知道如何表达这个问题......哈...任何有经验的人都知道如何这样做?

1 个答案:

答案 0 :(得分:0)

您的样式属性中包含无效信息。您的图片代码如下所示:

<img id = "myImage" src = "obama.jpg" style = "width: 100px height: 100px">

它应该是这样的:

<img id = "myImage" src = "obama.jpg" style = "width: 100px; height: 100px;">

注意添加的;

以下是动态设置图像样式的示例。我用一个函数来切换图像。

<button type = button onclick = "changeImage('bush');">Bush</button>
<button type = button onclick = "changeImage('obama')">Obama</button>
<p>Default is Obama </p>
<img id = "myImage" src = "https://whitehouse.gov1.info/photos_obama_face/obama-happy-flag.jpg" style = "width: 100px;  height: 100px" />

<script>
function changeImage(chump) {
    var img = document.getElementById('myImage');

    if(chump === 'obama') {
        img.src = 'https://whitehouse.gov1.info/photos_obama_face/obama-happy-flag.jpg';
        img.style.width = '100px';
        img.style.height = '100px';
    }
    else {
        img.src = 'http://www.capitolhillblue.com/wp-content/uploads/2011/07/071511bush.jpg';
        img.style.width = '200px';
        img.style.height = '200px';
    }
}
</script>