首页 > 解决方案 > 同时突出显示两个 div 单元格

问题描述

我有两个具有相同值的 div 表,当我单击一个单元格时,它会以指定的颜色突出显示。该代码分别适用于两个表。我需要的是当一个单元格被单击并突出显示时,另一个具有相同值的单元格也被突出显示。这是我的jsfiddle。谢谢您的帮助。

注意:我需要能够同时在两个表上突出显示多个不同的值。

html:

<input class="btn_colors" data-color="#9ac99d" type="button" name="green" id="green" value="Green" />

    <div class="table1">
    <div class="column">
    <div>6</div>
    <div>5</div>
    <div>4</div>
    <div>3</div>
    <div>2</div>
    <div>1</div>
    </div>

    <div class="table1">
    <div class="column">
    <div>6</div>
    <div>5</div>
    <div>4</div>
    <div>3</div>
    <div>2</div>
    <div>1</div>
    </div>

CSS:

.column {
  float: left;
}
.column div {
  border: 0.4px solid #CCC; font-family: Arial, Helvetica, sans-serif; font-size:11px;
  padding: 3px;
  margin: 0.02px;
  width: 16px;
  height: 12.9px;
  text-align: center;
  cursor: pointer;
}

.table1 { width: 30px; float:left;  margin:1px; margin-left:0px;margin-top:50px;}
.content { overflow: hidden; }

查询:

// variables
var buttons = document.getElementsByClassName('btn_colors');
var numbers = document.querySelectorAll('.column > div');
var current_color = document.getElementById('green').getAttribute('data-color');

// listener for button clicks
for (let i = 0, c = buttons.length; i < c; i++)
  buttons[i].addEventListener('click', set_color, {
    passive: false
  });

// listener for number cells
for (let i = 0, c = numbers.length; i < c; i++)
  numbers[i].addEventListener('click', set_bg, {
    passive: false
  });

// functions
function set_color(event) {
  event.preventDefault();
  current_color = this.getAttribute('data-color');
}

function set_bg(event) {
    if(this.classList.contains('clicked'))
  {
    this.classList.remove('clicked');
    this.style.backgroundColor = 'transparent';
    return ;
  }

  this.style.backgroundColor = current_color;
  this.classList.add('clicked');
}

标签: jquery

解决方案


您可以使用Array.find()方法在所有 div 元素中查找所需的 div。

function set_bg(event) {
    // Selecting all div elements and the finding the required div using Array.find()
    var anotherDiv = Array.from(document.querySelectorAll('div')).find(div => {
      return div != this && div.innerText == this.innerText; 
      // finds the div which have the same value as the current div.
    });

    if(this.classList.contains('clicked'))
  {
    this.classList.remove('clicked');
    this.style.backgroundColor = 'transparent';
    anotherDiv.classList.remove('clicked');
    anotherDiv.style.backgroundColor = 'transparent';
    return ;
  }

  this.style.backgroundColor = current_color;
  this.classList.add('clicked');
  anotherDiv.style.backgroundColor = current_color;
  anotherDiv.classList.add('clicked');
}

工作示例


推荐阅读