如何使用 javascript 在 2 css class 之间切换?

How to toggle between 2 css class using javascript?

参考 https://codepen.io/Maximusssssu/pen/MWrzpav 上的现场演示代码笔。请问如何在2 css class之间切换,也就是下面的红色正方形和红色三角形?当用户点击三角形按钮时,点击网格时它将代表一个三角形,当用户点击方形按钮时,当用户点击它时它将代表网格上的正方形。感谢您的阅读,祝您有愉快的一天:)

  <button onclick="triangle()">triangle</button>
  <button onclick="square()">square</button>



.red-dot {
  position:absolute; 
  width:15px; 
  height:15px;
  background:red;
  pointer-events: none;
}
.red-triangle {
  position:absolute; 
  width:15px; 
  height:15px;
  background:red;
  pointer-events: none;
  clip-path: polygon(50% 0, 100% 100%, 0 100%)
}

给你:

let classNameValue = "red-dot"

function triangle(){
  classNameValue = "red-triangle"
}

function square(){
  classNameValue = "red-dot"
}

我刚刚创建了一个全局变量并将其设置为您需要的className值,然后我将newDot.classList设置为变量值。

function showCoords(event) {
    // Calculate the position of the nearest grid intersection:

   var x = (Math.floor(event.clientX/50) * 50)+2 ;
   var y = (Math.floor(event.clientY/50) * 50)+2 ;
    var coords = "X coordinates: " + x + ", Y coordinates: " + y;
    document.getElementById('showCoords').innerHTML = coords;
    // Create a new red dot:
    let newDot = document.createElement('span');
    // Add the CSS class:
    newDot.className = classNameValue;
    // Set coordinates:
    newDot.style.top = y + 'px';
    newDot.style.left = x + 'px';
    // Add the new element to the end of the body:
    document.body.appendChild(newDot);
  }