简体   繁体   English

使用javascript更改属性的值

[英]Changing the Value of an Attribute using javascript

Getting my script down to the bare bones, I have followed the example of the w3schools.com ( https://www.w3schools.com/js/js_htmldom_html.asp ) for: document.getElementById(id).attribute = new value. 为了使我的脚本简明扼要,我遵循了w3schools.com( https://www.w3schools.com/js/js_htmldom_html.asp )的示例:document.getElementById(id).attribute =新值。 Their example: 他们的例子:

<!DOCTYPE html>
<html>
<body>

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

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

</body>
</html>

Here is mine. 这是我的。 I get no error messages on the Chrome console. 我在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>

You can see the result at http://newthaimassage.com/index3.php . 您可以在http://newthaimassage.com/index3.php上查看结果。 Here is the script not stripped down. 这是未精简的脚本。

<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>

Currently I am using CSS media queries to show images by window size, but using background images I can not use CSS animation, which is my ultimate goal here. 目前,我正在使用CSS媒体查询按窗口大小显示图像,但是使用背景图像却无法使用CSS动画,这是我的最终目标。 Any help on this would be greatly appreciated. 任何帮助,将不胜感激。

您有错字,将scr更改为src

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

document.getElementById("indexPhoto").src

In JavaScript: 在JavaScript中:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM