2013-11-28 73 views
0

我利用我的一些業餘時間學習SOM基本編程,並且我碰到了一種凹凸。 以下腳本有效,但完全沒有優雅,我懷疑它可以用更少的代碼解決。更改元素級點擊,更優雅的解決方案

<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個引腳,因此引腳類變化的JavaScript似乎不必要的長和殘餘。

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"; 
} 

我需要25 + 1的這些(25的onclick引腳和一個用於復位一旦網站重裝) 不知道,如果是相關的,但這裏是 -

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? – cocco

+0

哦,和byttKlasse_1一樣,只是naal_1會變成「naal brukbar」,而naal_2變成「over circus」 – Freshman

回答

2

這樣的事情? (我測試僅在鉻)

JS

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

額外的樣式....

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

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

+0

是的,就像那樣:D!謝謝你們! – Freshman

相關問題