當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


d3.js selection.classed()用法及代碼示例

selection.classed()函數用於將類設置為所選元素。此函數也可以用於將類設置為所選的特定元素。

用法:

selection.classed(names[, value]);

參數:above-given函數采用上麵給出和下麵描述的兩個參數:

  • name:它是要賦予所選元素的類的名稱。
  • value:是布爾值,即設置或取消設置類的true或false。

返回值:此函數不返回任何內容。

範例1:設置類名稱。



HTML


<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" path1tent="width=device-width, 
                    initial-scale=1.0">
    <script src="https://d3js.org/d3.v4.min.js">
    </script>
</head>
  
<body>
    <div>
        <a>GeeksforGeeks</a>
    </div>
  
    <script>
  
        // Sets the class to the a tag
        var a = d3.select("a")
            .classed("className", true);
          
        // This will select the anchor tag
        var divselect = document.querySelector(".className");
        console.log(divselect.innerHTML);
    </script>
</body>
  
</html>

輸出:

GeeksforGeeks

範例2:取消設置類名稱。

HTML


<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" path1tent="width=device-width, 
                    initial-scale=1.0">
    <script src="https://d3js.org/d3.v4.min.js">
    </script>
</head>
  
<body>
    <div>
        <p class="classGiven classGiven2">
            GeeksforGeeks
        </p>
    </div>
  
    <script>
  
        // Unsets the class named classGiven
        // to the "p" tag
        var a = d3.select("p")
            .classed("classGiven2", false);
  
        // This will select the "p" tag
        var divselect = document
            .querySelector(".classGiven");
              
        console.log(divselect.innerHTML);
  
        // This will not select the "p" tag
        // As the classGiven 2 is unset
          
        var divselect = document
            .querySelector(".classGiven2");
  
        console.log(divselect);
    </script>
</body>
  
</html>

輸出:

GeeksforGeeks
null

相關用法


注:本文由純淨天空篩選整理自tarun007大神的英文原創作品 D3.js selection.classed() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。