2013-11-28 5 views
0

기본 프로그래밍을 배우기 위해 여가 시간을 사용하고 있습니다. 다음 스크립트는 작동하지만 우아하지 않습니다. 그리고 훨씬 적은 코드로 해결할 수 있습니다.더 우아하고 우아한 클릭으로 요소 클래스 변경

<div class="naal brukbar" id="naal_1" onclick="writeText(brukbar); byttKlasse_1();"></div> 
<div class="naal circus" id="naal_2" onclick="writeText(circus); byttKlasse_2();"></div> 

이 경우 맵은 핀으로 구성된 CSS 조정자입니다. 위가 기본값입니다.

"문제"당신이 그것을 부를 수 있다면, 나는 20 개 이상의 핀을 가지고 있고, therfore 핀 - 클래스 - 변경 - 자바 스크립트는 불필요한 긴 잔여 것 같습니다.

JS :

function byttKlasse_1() 
{ 
    document.getElementById("naal_1").className = "over brukbar"; 

    document.getElementById("naal_2").className = "naal circus"; 
    document.getElementById("naal_5").className = "naal micro"; 
    document.getElementById("naal_6").className = "naal disko"; 
    document.getElementById("naal_7").className = "naal lundgreen"; 
    document.getElementById("naal_8").className = "naal kos"; 
    document.getElementById("naal_9").className = "naal raus"; 
    document.getElementById("naal_10").className = "naal mormors"; 
    document.getElementById("naal_11").className = "naal samfundet"; 
} 

가 나는 관련이 있는지 알고하지 마십시오 (사이트를 다시로드 한 번 리셋에 대한 onclick을 핀에 대한 25 일)이 25 + 1 이 필요하지만, 여기입니다 -

CSS :

.naal   { 
       position: relative; 
       background-image: url('bilder/naal.png'); 
       width:12px; 
       height:20px; 
       opacity:1; 
       } 

.over   { 
       position: relative; 
       background-image: url('bilder/naal_aktiv.png'); 
       width:12px; 
       height:20px; 
       opacity:.9; 
       cursor:pointer; 
       } 
.brukbar {top: -270px; left: 285px;} 
.circus  {top: -450px; left: 368px;} 

는 어떻게 든이 "배열 그것을"수 있습니까? 지도에서 핀의 상대적 위치로 인해 하나의 클래스 만 변경할 수는 없습니다.

+0

byttKlasse_2 ​​무엇합니까 http://jsfiddle.net/bg2Hw/3/? – cocco

+0

아, byttKlasse_1과 동일합니다. naal_1은 "naal brukbar"로 변경되고 naal_2는 "over circus"로 변경됩니다. – Freshman

답변

2

그런 식 으로요?

JS (I은 크롬 시험)

var current='x'; 
function smallBoxesHandler(e){ 
if(current!='x'){ 
    bigBox.childNodes[current].classList.remove('checked'); 
} 
current=Array.prototype.slice.call(e.target.parentNode.childNodes).indexOf(e.target); 
bigBox.childNodes[current].classList.add('checked'); 
} 
var bigBox=document.createElement('div'); 
bigBox.addEventListener('click',smallBoxesHandler,false); 
document.body.appendChild(bigBox).innerHTML=new Array(11+1).join('<div></div>'); 

CSS

body>div{ 
width:220px; 
border:1px solid rgba(0,0,0,0.5); 
overflow:auto; 
} 
body>div>div{ 
width:20px; 
height:20px; 
float:left; 
box-sizing:border-box; 
} 
body>div>div:hover{ 
border:1px dotted rgba(0,255,0,0.5); 
} 
body>div>div.checked{ 
border:1px dotted rgba(0,255,0,0.5); 
background-color:red; 
} 

http://jsfiddle.net/bg2Hw/

EDIT

,617 여분의 스타일

....

http://jsfiddle.net/bg2Hw/1/

또는

http://jsfiddle.net/bg2Hw/2/

,

+0

네, 그런 식 으로요! D! 너 한 무리 고마워! – Freshman

관련 문제