2013-11-20 2 views
0

내 질문에 라디오 버튼을 사용하는 양식을 만듭니다.라디오 버튼을 사용하여 배경색 변경

라디오 버튼이 각각 다른 값을 가진 배경색을 변경하고 싶습니다.
예. 2. 버튼이 파란색으로 바뀌면 버튼 1이 빨간색으로 바뀝니다.

자바 스크립트

function changeColour() { 
    if("r") 
     document.body.style.backgroundColour="#FF0000"; 
    if("b") 
     document.body.style.backgroundColour="#0000FF"; 
    if("p") 
     document.body.style.backgroundColour="#FF00FF"; 
} 

HTML

<div id= "genre"> 
    What do you bust a move to? 
    <form name="music" method="post" action=""> 
     <p> 
     <input type="radio" name="music" value="radio" onBlur="changeColour("b")">Blues 
     <input type="radio" name="music" value="radio" onBlur="changeColour("r")">Rock 
     <input type="radio" name="music" value="radio" onBlur="changeColour("p")">Pop 
    </form> 
</div> 

나는이 새로운 오전 그래서 어떤 도움을 환영합니다. 감사.

답변

1

가까운 사이. 이벤트를 onclick으로 바 꾸었습니다. 배경색은 Color가 아닙니다. 다음은 예입니다. - http://jsfiddle.net/6jt8h/

<div id= "genre"> 
What do you bust a move to? 
<br> 
<br> 
<form name="music" method="post" action=""> 
<p> 
<input type="radio" name="music" value="radio" onClick="changeColour('b')">Blues 
<br> 
<input type="radio" name="music" value="radio" onClick="changeColour('r')">Rock 
<br> 
<input type="radio" name="music" value="radio" onClick="changeColour('p')">Pop 
<br> 
</form> 
</div> 


function changeColour(value) 
{ 
    var color = document.body.style.backgroundColor; 
    switch(value) 
    { 
     case 'b': 
      color = "#FF0000"; 
     break; 
     case 'r': 
      color = "#0000FF"; 
     break; 
     case 'p': 
      color = "#FF00FF"; 
     break; 
    } 
    document.body.style.backgroundColor = color; 
} 
1
  1. 문장 사이에는 html이 없습니다. 작은 따옴표로 값을 전달하는 <br>

  2. 를 제거하고

  3. 사용의 onclick 함수 선언에서 사용하지

  4. 가치 및 onblur = "라디오는"

  5. 컬러 유용하지 않다 자바 스크립트에서 미국 영어로 표기됩니다. 함수 이름의 철자가 changeColur 일 수 있지만 backgroundColor는 o가되어야합니다. 즉, 사용자가

    function changeColour(val) { 
        var styleBgCol = document.body.style.backgroundColour; 
        if (val=="r") { 
        styleBgCol ="#FF0000"; 
        } 
        else if (val=="b") { 
        styleBgCol="#0000FF"; 
        } 
        else if (val=="p") { 
        styleBgCol="#FF00FF"; 
        } 
    } 
    
    그렇게} {에서 포장도

그것은 간주됩니다 좋은 연습 텍스트를 클릭 할 수 있도록 HTML을
<input type="radio" name="music" value="radio" onClick="changeColour('b')">Blues

  • 추가 라벨된다는 의미입니다

    코드 작성 방법은 다음과 같습니다.

    ,988,887,

    <!doctype html> 
    <html> 
    <head> 
    <meta charset="utf.8" /> 
    <title>Rock 'n Roll</title> 
    <script> 
    var cols = { 
        "r":"#FF0000", 
        "b":"#0000FF", 
        "p":"#FF00FF" 
    } // no comma after the last 
    window.onload=function() { // when the page loads 
        var rads = document.getElementsByName("music"); // all rads named music 
        for (var i=0;i<rads.length;i++) { 
        rads[i].onclick=function() { 
         document.body.style.backgroundColor=cols[this.value]; 
        } 
        } 
    } 
    </script> 
    </head> 
    <body> 
    <div id= "genre"> 
        What do you bust a move to? 
        <br> 
        <br> 
        <form name="music" method="post" action=""> 
        <input type="radio" name="music" id="bRad" value="b"><label for="bRad">Blues</label> 
        <br> 
        <input type="radio" name="music" id="rRad" value="r"><label for="rRad">Rock</label> 
        <br> 
        <input type="radio" name="music" id="pRad" value="p"><label for="pRad">Pop</label> 
        <br> 
        <br> 
        </form> 
    </div> 
    </body> 
    </html> 
    
  • 0

    다음과 같이해야합니다

    <form name="music" method="post" action=""> 
    <p> 
    <input type="radio" name="music" value="radio" onBlur="changeColour('b');">Blues 
    <br> 
    <input type="radio" name="music" value="radio" onBlur="changeColour('r');">Rock 
    <br> 
    <input type="radio" name="music" value="radio" onBlur="changeColour('p');">Pop 
    <br> 
    </form> 
    
    
    function changeColour(color) { 
        if(color=="r"){ 
        document.body.style.backgroundColour="#FF0000"; 
        }else if(color=="b"){ 
        document.body.style.backgroundColour="#0000FF"; 
        }else if(color=="p"){ 
        document.body.style.backgroundColour="#FF00FF"; 
        } 
    } 
    
    +0

    Miss-spelled attribute – mplungjan

    0

    내가 강력하게 HTML에서 자바 스크립트를 제거하고, 결합 자바 스크립트를 사용하는 것이 좋습니다하려는 이벤트 처리 (더 쉽게 유지 보수 코드를 만들고, HTML을 통해 업데이트/변경하기 위해 사냥 할 필요가 없으므로; 그것은 모두 당신이 구현하는 JavaScript 파일/라이브러리에 있어야합니다). 다음 자바 스크립트와

    <div id="genre">What do you bust a move to? 
        <form name="music" method="post" action="#"> 
         <input type="radio" name="music" value="radio"/>Blues 
         <input type="radio" name="music" value="radio" />Rock 
         <input type="radio" name="music" value="radio" />Pop</form> 
    </div> 
    

    :

    function changeColour (e) { 
        // e.target is the element that triggered the event we're reacting to: 
        var el = e.target; 
        /* el.nextSibling.nodeValue is the text of the next sibling-node, 
         toLowerCase() turns that text into lower-case, 
         [0] gets the first letter of that text: 
        */ 
        switch (el.nextSibling.nodeValue.toLowerCase()[0]) { 
         case 'b' : 
          // 'this' is the element that's handling the event (the div): 
          this.style.backgroundColor = '#00f'; 
          break; 
         case 'r' : 
          this.style.backgroundColor = '#f00'; 
          break; 
         case 'p' : 
          this.style.backgroundColor = '#f0f'; 
          break; 
        } 
    } 
    
    /* gets the element with the id of 'genre', and adds a listener to that 
        element, listening for the change event, and triggering the 'changeColour' 
        function when it's detected: 
    */ 
    document.getElementById('genre').addEventListener('change', changeColour, true); 
    

    JS Fiddle demo 그건 내가 다음 HTML을 제안 거라고 말했다.

    또한, 나는 label (텍스트 자체)를 클릭하면 해당 텍스트 관련 input을 확인 할 수 있도록하기 위하여, label 요소로 input 요소를 포장 좋을 것 :

    <div id="genre">What do you bust a move to? 
        <form name="music" method="post" action="#"> 
         <label> 
          <input type="radio" name="music" value="radio" />Blues</label> 
         <label> 
          <input type="radio" name="music" value="radio" />Rock</label> 
         <label> 
          <input type="radio" name="music" value="radio" />Pop</label> 
        </form> 
    </div> 
    

    JS Fiddle demo합니다.

    그것은 예를 들어, 색상으로 선택을 연결하는 자바 스크립트 객체를 사용할 수도 있습니다

    function changeColour(e) { 
        // sets the letter-colour options: 
        var colorMap = { 
         'b' : '#00f', 
         'r' : '#f00', 
         'p' : '#fof' 
        }; 
        var el = e.target, 
         checked = el.nextSibling.nodeValue.toLowerCase()[0]; 
        /* if the relevant letter is in the colorMap object 
         (and generates a truthy value), we set the background-color 
         to whatever is retrieved: 
        */ 
        if (colorMap[checked]){ 
         this.style.backgroundColor = colorMap[checked]; 
        } 
    } 
    
    document.getElementById('genre').addEventListener('change', changeColour, true); 
    

    JS Fiddle demo.

    +0

    진지하게? nodeValues, 형제 및 이벤트 리스너를 멍청이에 배치? 나는 onload와 object를 잘 사용했지만, 맨 위에있는 것을 찾았습니다. evenListener와 nextSibling.nodeValue의 부가가치가 훨씬 더 읽기 쉬운 스크립트보다 무엇인지 말해 주시겠습니까? – mplungjan

    +0

    '추가 된 가치'? 그것은 논쟁의 여지가 있습니다. 나는이 방법을 선택했습니다. 나는 당신의 반복을 피하고 대안을 제공 할 수 없기 때문입니다. 또한'onload','onclick' 등을 사용하는 것을 싫어합니다. 개인 선택입니다. 솔직히 복잡한 응답으로 보지는 않습니다. –

    +0

    좋습니다. addEventListener는 브라우저 간 호환이 아니므로 절대로 사용하지 않으며 둘 이상을 추가 할 필요가 없습니다. 이러한 복잡성이 필요하다면 jQuery를 사용한다. nodeValues에 관해서는, 나는 자아가 의미하는 바를보기 위해 두 번 읽어야하고, 어제 JS를 작성하지 않았다.) – mplungjan

    관련 문제