How to make the background color of a div deepen with the continuous click of the mouse? how to write the js code?

can be a little more complex, such as the left button keeps clicking, deepening, from light red to crimson, until it can not be deepened, right-click to achieve reverse operation!

May.22,2021

Color can be adjusted as needed

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    div {
      width: 300px;
      height: 300px;
      border: 2px solid -sharp000;
    }
  </style>
</head>

<body oncontextmenu="return false">
  <div id='div' onmousedown='divClick(event)'></div>

  <script>
    var bgColor = ['00', '11', '22', '33', '44', '55', '66', '77', '88', '99', 'aa', 'bb', 'cc', 'dd', 'ee', 'ff'];
    var div = document.getElementById('div');

    function changeBg(index) {
      div.setAttribute('style', 'background-color: -sharp' + bgColor[index] + '0000')
      div.setAttribute('data-index', index)
    }
    changeBg(0);

    function divClick(event) {
      var mouse = event.button
      var index = div.getAttribute('data-index')
      if(index == 0 && mouse == 0){
        indexPP
      }else if(index == (bgColor.length - 1) && mouse == 2){
        index--
      }else if (index > 0 && index < (bgColor.length - 1)) {
        if (mouse == 0) {//
          indexPP
        } else if (mouse == 2) {//
          index--
        }
      }
      changeBg(index);
    }
  </script>
</body>

</html>

Color deepening change, you can start with color hexadecimal
all that is left is binding the mouse event to change the RGB value


you can use the filter. The specific code

const step = 1;
const div = document.getElementById('div');
let percent = 100;
function darken() {
   percent += step;
   div.style.filter =  `brightness(${percent}%)`;
}
div.addEventListener('click', darken, false)

first of all, I will help you understand your specific principles of controlling rgba

.
=>   rgbr  0=>255
=>   rgbgb 255=>0

<script>
window.onload=function(){
    let num=255;
    document.onclick=function(){
        num--;
        if(num<=0)num=0;
        div1.style.background='rgb(255,'+num+','+num+')';
    }
}
</script>
    <div id="div1" style="width:50px; height:50px;"></div>

use hsv

Menu