同时突出显示两个div单元

时间:2018-10-06 08:25:30

标签: jquery

我有两个具有相同值的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; }

jQuery:

// 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');
}

2 个答案:

答案 0 :(得分:2)

您可以使用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');
}

Working Example

答案 1 :(得分:0)

嗨,您可以在下面尝试或使用此代码:

size