ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • img 변경 예제
    javascript ES5 정리 2020. 9. 28. 17:43

    text명으로 변경

    html

     <section id="imgt1">
          <img src = "image/img1.jpg" class="img1"></br>
          <input type="text" class="imgtext"></br>
          <input type="button" class="btn" value="변경">
        </section>

     

    js

    window.addEventListener("load", function(){
      var imgt1 = document.querySelector("#imgt1")
      var img1 = imgt1.querySelector(".img1");
      var btn = imgt1.querySelector(".btn");
      var imgtext = imgt1.querySelector(".imgtext");
       btn.onclick = function(){
          img1.src = "image/"+imgtext.value+".jpg";
       }
       
    });

     

    옵션바 변경

    html

    <select id="selcimg">
            <option value="img1.jpg">img1</option>
            <option value="img2.jpg">img2</option>
          </select>

     

    js

    window.addEventListener("load", function(){
      var imgt1 = document.querySelector("#imgt1")
      var img1 = imgt1.querySelector(".img1");
      var btn = imgt1.querySelector(".btn");
      var imgtext = imgt1.querySelector(".imgtext");
      var selcimg = imgt1.querySelector("#selcimg");
       btn.onclick = function(){
          img1.src = "image/"+imgtext.value+".jpg";
          img1.src = "image/"+selcimg.value;
       }
       
    });

     

    html5에서 추가된 datalist를 사용한 변경

    html

    <input class = "datalist" list ="img-list">
          <datalist id ="img-list">
            <option value="img1.jpg">img1</option>
            <option value="img2.jpg">img2</option>
          </datalist>

     

    js

    window.addEventListener("load", function(){
      var imgt1 = document.querySelector("#imgt1")
      var img1 = imgt1.querySelector(".img1");
      var btn = imgt1.querySelector(".btn");
      var imgtext = imgt1.querySelector(".imgtext");
      var selcimg = imgt1.querySelector("#selcimg");
      var datalist = imgt1.querySelector(".datalist");
       btn.onclick = function(){
          img1.src = "image/"+imgtext.value+".jpg";
          img1.src = "image/"+selcimg.value;
          img1.src = "image/"+datalist.value;
       }
       
    });
Designed by Tistory.