使用javascript更改属性的值

时间:2017-07-07 15:08:05

标签: javascript jquery

让我的脚本简单到底,我已经按照w3schools.com(https://www.w3schools.com/js/js_htmldom_html.asp)的示例进行了:document.getElementById(id).attribute = new value。他们的例子:

<!DOCTYPE html>
<html>
<body>

    <img id="myImage" src="smiley.gif">

<script>
    document.getElementById("myImage").src = "landscape.jpg";
</script>

</body>
</html>

这是我的。我在Chrome控制台上没有收到任何错误消息。

<body>

    <img id = "indexPhoto" src = 
        "newthaiimages/indexPhotos/indexPhoto_320.jpg" 
         width="320" height="474" alt="hero sepia toned photo of Thai 
         temple next to a river"/>

<script>

    document.getElementById("indexPhoto").scr = 
        "newthaiimages/indexPhotos/indexPhoto_450.jpg";

</script>

</body>

您可以在http://newthaimassage.com/index3.php看到结果。这是没有删除的脚本。

<script>

    window.onload = function() {

       var w = window

   var x = w.innerWidth 

switch(w.innerWidth){ 

    case x <= 320:

    break;      

    case x <= 768:

        document.getElementById("indexPhoto").scr ="indexPhoto_450.jpg";

    break;

    case x <= 1024:

        document.getElementById("indexPhoto").scr ="indexPhoto_835.jpg"; 

    break;

    case x <= 1420:

        document.getElementById("indexPhoto").scr ="indexPhoto_1000.jpg"; 

    break;

    default:

        document.getElementById("indexPhoto").scr ="indexPhoto_1200.jpg"; 

}}

</script>

目前我正在使用CSS媒体查询按窗口大小显示图像,但使用背景图像我无法使用CSS动画,这是我的最终目标。对此的任何帮助将不胜感激。

4 个答案:

答案 0 :(得分:3)

您输入错误,将scr更改为src

答案 1 :(得分:1)

您的document.getElementById("indexPhoto").scr应该是:

document.getElementById("indexPhoto").src

答案 2 :(得分:0)

在JavaScript中:

var ele=document.getElementById("indexPhoto");
ele.setAttribute('src',"landscape.jpg");

答案 3 :(得分:0)

这是语法错误,您应该使用document.getElementById("indexPhoto").src代替document.getElementById("indexPhoto").scr,这只是一个字母问题。