简体   繁体   English

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

[英]How to toggle between 2 css class using javascript?

Refering to a live demo codepen at https://codepen.io/Maximusssssu/pen/MWrzpav .参考https://codepen.io/Maximusssssu/pen/MWrzpav 上的现场演示 codepen May I ask how can I toggle between 2 css class that is red square and red triangle represented below?请问如何在 2 css class 之间切换,即下面的红色正方形和红色三角形? When user click on triangle button, it will represent a triangle when grid is clicked and when click on square button it will be a square on grid when user click on it.当用户点击三角形按钮时,点击网格时它将代表一个三角形,当用户点击方形按钮时,当用户点击它时它将代表网格上的正方形。 Thank you for reading and have a nice day:)感谢您的阅读,祝您有美好的一天:)

  <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%)
}

Here you go:给你go:

let classNameValue = "red-dot"

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

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

I just created a global variable and I set it to the className value you need, and then I just set the newDot.classList to the variable value.我刚刚创建了一个全局变量并将其设置为您需要的 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);
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM