簡體   English   中英

單擊JavaScript更改類中所有元素的顏色

[英]Change color of all elements in class on click JavaScript

我有一個人體圖像(SVG)。 我想使用JavaScript,這樣,當我單擊特定區域(例如,小腿)時,所有具有“小腿”類(即使未單擊)的元素的顏色也都發生了變化–對用戶來說更容易。

這是我目前擁有的JavaScript:

function changeclassstyle() {
  var c = document.getElementsByClassName("lower-leg");
  for (var i=0; i<c.length; i++) {
    c[i].style.fill = "red";
  }
}

此代碼的問題在於,僅將其概括為“小腿”。 我可能有十幾個我想為此工作的類,並且認為編寫12個函數的效率不高,唯一的變化就是類名。 有沒有一種方法可以抓住選擇的類,然后將其輸入到函數中?

-

另外,我很想弄清楚一旦選擇了身體的這一部分,我可以如何存儲類名。 最后,我想將選擇內容以及其他輸入的信息存儲在數據庫中。 但是,除非有人可以提供幫助,否則這可能是一個未來的問題!

這是我的操作方法(已在div上進行了測試)。

我們正在做的是將event對象傳遞給事件處理程序(您的changeclassstyle()函數)。 然后,它使用被單擊項的類(事件目標的類),並使用相同的類名更改該頁面上的所有其他內容,以使用所需的新CSS樣式。

 function changeclassstyle(e) {

           // Get all items that have the same class as the item that was clicked
            var limbs = document.getElementsByClassName(e.target.className); // for div's and the like

           // var limbs = document.getElementsByClassName(e.target.className.baseVal); // turns out this is needed for SVG items 


           // "limbs" is an HTMLCollection, not an array, so functions like .foreach won't work; C-style for-loops or modern for/let/of loops are better

            for (let item of limbs) {
                item.style.backgroundColor = 'red'; 
              // item.style.fill = 'red';  // This is probably what you need for your SVG items
            }

         // You could still use your C-style for loop if needed/wanted
            /*
               for (var i=0; i<limbs.length; i++) {
                limbs[i].style.fill = "red";
               }
            */
        }

onchange調用看起來像這樣(以我的div為例):

        <div class="upper-arm" onclick="changeclassstyle(event)">
        </div>

        <div class="lower-leg" onclick="changeclassstyle(event)">
        </div>

帶有簡單div的整個示例。

<html>
    <head><title>stuff</title></head>
    <body>
        <script type="text/javascript">
        function changeclassstyle(e) {
            // For debugging. You may want to expand 'e' here in your browser's debug tools if you're not seeing the values you need/want
            console.log(e)
            var limbs = document.getElementsByClassName(e.target.className.baseVal);
            for (let item of limbs) {
                item.style.backgroundColor = 'red';  
            }
        }
        </script>

        <style type="text/css">
        div {
            height: 100px;
            width: 100px;
            background-color: 'white';
            border: 1px solid black;
        }
        </style>

        <div class="upper-arm" onclick="changeclassstyle(event)">
        </div>
        <div class="upper-arm" onclick="changeclassstyle(event)">
        </div>
        <div class="upper-arm" onclick="changeclassstyle(event)">
        </div>

        <div class="lower-leg" onclick="changeclassstyle(event)">
        </div>
        <div class="lower-leg" onclick="changeclassstyle(event)">
        </div>
        <div class="lower-leg" onclick="changeclassstyle(event)">
        </div>
    </body>
</html>

您可以在傳遞classcolor函數中使用參數,如下所示

function changeStyle(cls,clr) {
  let elems = document.getElementsByClassName(cls);
  if(!elems) return;
  for (let elem of elems) {
      elem.style.color = clr;
  }
}

按照我說過的許多類的迭代,您可以將類存儲在數組中並對其進行迭代。

  let classes = ['one','two','three','four'];

  classes.forEach(function (cls) {
    changeStyle(cls,"red");
  });

如果您想測試/實驗,可以在這里玩小提琴: https : //jsfiddle.net/thrL5uqw/8/

注意:根據需要更改樣式屬性,目前我已將顏色用於演示

我參加聚會有點晚了,但這是我對這個問題的看法。

就像其他人告訴您的那樣,您需要在函數中使用一個附加參數來指定要修改元素的類(或嘗試從單擊的元素中找出該類),因此您應該具有以下內容:

/**
 * This function will handle the click event on one of the part of the SVG.
 * @param {string} lClass This the class of the element to modify
 */
function handleClick(lClass) {
  for (let e of document.getElementsByClassName(lClass)) {
    // Here you can do all the changes you need on the SVG element.
    e.style.fill = "red";
  }
}

在事件綁定方面,您可以像其他建議的那樣做,並在HTML元素上添加onclick事件綁定屬性,也可以使用addEventListener函數將其綁定到JS中(這樣就不必重復每個SVG元素的onclick屬性)。

// For each element of all the listed class, bind the "click" event to the handleClick function
const listenClass = [/*List of your classes*/];
for (let l of listenClass) {
  for (let e of document.getElementsByClassName(l)) {
    e.addEventListener('click', handleClick.bind(this, l));
  }
}

演示: https//plnkr.co/edit/gay2yBaVi5QD868fsTa6?p = preview

希望對您有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM