第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

JavaScript。點(diǎn)擊一個(gè)改變顏色,點(diǎn)擊另一個(gè)恢復(fù),很多元素,怎么做?

JavaScript。點(diǎn)擊一個(gè)改變顏色,點(diǎn)擊另一個(gè)恢復(fù),很多元素,怎么做?

慕村225694 2022-05-26 11:07:09
我試圖給 .svg 世界地圖一個(gè) JavaScript“點(diǎn)擊更改顏色”功能。預(yù)期行為:單擊一個(gè)國家更改其顏色,單擊另一個(gè)國家更改顏色,但之前單擊恢復(fù)為默認(rèn)顏色。我現(xiàn)在的錯(cuò)誤:單擊一個(gè)國家,它的顏色改變了,但單擊另一個(gè),以前的顏色保持不變。有錯(cuò)誤的代碼(意外):svg結(jié)構(gòu):<g name="us"><path>...</path></g><g name="au"><path>...</path></g><g name="es"><path>...</path></g>.....<g name="ca"><path>...</path></g>JavaScript 部分:(function () {  var world = document.getElementById("world");  // The svg file  world.addEventListener("load", function () {    var doc = world.getSVGDocument();    doc.addEventListener("click", function (e) {     e.preventDefault();      var target = e.target,          target.style.fill = "#eee";    });  });}());需要純 JavaScript,不需要 jQuery。如果元素(國家)是三個(gè)或五個(gè),我可以這樣做,但是元素太多,有沒有一種緊湊的方法來獲得這種效果?感謝您的關(guān)注,如果可以,請(qǐng)幫助我。:)
查看完整描述

1 回答

?
紫衣仙女

TA貢獻(xiàn)1839條經(jīng)驗(yàn) 獲得超15個(gè)贊

您可以在單擊時(shí)取消選擇所有元素,然后選擇被單擊的元素:


const svg = document.getElementById('world');

const elements = svg.getElementsByTagName('g');


svg.onclick = ({ target }) => {

  // make sure we clicked on a group or a child of one

  // and do nothing if we havent

  const g = target.closest('g'); 

  if (!g) return;

  

  // remove selected class from all

  // and add it to the one clicked

  [...elements].forEach(e => e.classList.remove('selected'));

  g.classList.add('selected');

};

.selected {

  fill: yellow;

}

<svg id="world" width="100" height="100" viewBox="0 0 30 30">

<g data-country="1"><rect x="0" y="0" width="10" height="10"/></g>

<g data-country="2"><rect x="10" y="10" width="10" height="10"/></g>

<g data-country="3"><rect x="20" y="20" width="10" height="10"/></g>

<g data-country="4"><rect x="0" y="20" width="10" height="10"/></g>

</svg>


查看完整回答
反對(duì) 回復(fù) 2022-05-26
  • 1 回答
  • 0 關(guān)注
  • 356 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)