Javascript Function that changes Text Color, Hyperlink Color, and Image

后端 未结 1 780
小蘑菇
小蘑菇 2020-12-22 10:14

Hi,

I need help with a class assignment. We were given an HTML file for a pretend business, \"Castaway Vacations LLC\". The first step in the assignment is

相关标签:
1条回答
  • 2020-12-22 10:43

    ok, for starters to change color of something you just need to do something like this

    function change_color(){ 
     document.body.style.color = "red";  // this will change the color of the text to RED
     document.getElementById("image_to_change").src = "something.jpg"; // change img src
    }
    

    to use the function just add the call to the function where you want it, for example

      <a onClick="change_color();" href="#">Romantic</a><br><br>
    

    well, its already accepted answer, but just wanted to complete it, to change the img src of, first you need to add an id for that img, for example

    <td align="center"><img id="image_to_change"src="orig_main.jpg"><br><i>Your Vacation Awaits!
    

    after you added the id, you can see how i added this line to the "change_color" function

    document.getElementById("image_to_change").src = "***SOURCE_TO_YOUR_IMAGE***";
    

    * Working Code * OK, here is the working fiddle http://jsfiddle.net/8ntdbek3/1/ i changed a few things to make it work, first, you need to understand that when you give an "ID" to something, in this case to the img (you gave the id "rom_main.jpg") the ID is what you need to use to call that element, so when you are using

    document.getElementById("orig_main.jpg").src = "rom_main.jpg";
    

    it should go

    document.getElementById("rom_main.jpg").src = "rom_main.jpg";
    

    since you gave it the id "rom_main.jpg" in this line, and the id "orig_main.jpg" does not exist!

     <td align="center"><img id=**"rom_main.jpg**" src="orig_main.jpg"><br><i>Your Vacation Awaits!
    

    also its important to note that you can put ANY id that you want, so repeating the name of the jpg file its something that i would not recommend, since it leads to confusion.

    I changed the ID to something more readable and thats it. if you still need help comment below and i'll do my best to help you.

    * EDIT to change color *

    ok, finally i added a few lines of code to change the color of EVERY element in your page, for each onclick i adde these lines:

    var list = document.getElementsByTagName("a");     
    for (i = 0; i < list.length; i++) { 
      list[i].style.color = "red";  
    }
    

    as you can see, i get in a list every element with the tag "a", then every element i turn it into "red" (or the color you want).

    here is the working fiddle http://jsfiddle.net/8ntdbek3/3/

    regards.

    0 讨论(0)
提交回复
热议问题