Refiriéndose a un codepen de demostración en vivo en https://codepen.io/Maximusssssu/pen/MWrzpav . ¿Puedo preguntar cómo puedo alternar entre la clase 2 css que es un cuadrado rojo y un triángulo rojo representado a continuación? Cuando el usuario haga clic en el botón del triángulo, representará un triángulo cuando se haga clic en la cuadrícula y cuando haga clic en el botón cuadrado, será un cuadrado en la cuadrícula cuando el usuario haga clic en él. Gracias por leer y que tengas un buen día :)
<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%) }Aquí tienes:
let classNameValue = "red-dot" function triangle(){ classNameValue = "red-triangle" } function square(){ classNameValue = "red-dot" }Acabo de crear una variable global y la configuré en el valor className que necesita, y luego configuré newDot.classList en el valor de la variable.
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); }