css 在Hover上为动态内容更改另一个div的背景Div- JQuery

yh2wf1be  于 2023-03-25  发布在  jQuery
关注(0)|答案(2)|浏览(130)

我有一个链接列表和一个动态生成的标记列表:
其结构如下所示:

<div>
  <a id="link{{i}}>Link {{i}}</a>
</div>

<div>
  <div id="marker{{j}}">Marker {{j}}</div>
</div>

当内容是动态生成的-它最终看起来像这样:

<div>
  <a id="link1">Link 1</a>
  <a id="link2">Link 2</a>
  <a id="link3">Link 3</a>
</div>

<div>
  <div id="marker1">Marker 1</div>
  <div id="marker2">Marker 2</div>
  <div id="marker3">Marker 3</div>
</div>

有没有一种方法可以在jQuery中编写一个函数,确保当用户在链接1上悬停时-标记1的背景颜色变为黄色,在链接2上-标记2的背景颜色变为黄色等等......

jhdbpxl9

jhdbpxl91#

我已经创建了一个基本的例子,我添加了一个通用的marker类来样式化标记。
示例:

$(document).on("mouseenter", "a", function() {

  // get the id of the hovered element
  let elemId = $(this).attr("id");
  // parse the numeric value
  let elemIndex = parseNumber(elemId);

  // add active class to related marker
  $('#marker' + elemIndex).addClass('active');

});

$(document).on("mouseleave", "a", function() {

  let elemId = $(this).attr("id");
  let elemIndex = parseNumber(elemId);

  $('#marker' + elemIndex).removeClass('active');

});

function parseNumber(str) {
  return parseInt(str.replace(/[^\d]/g, ''), 10);
}
.marker {
  transition: .5s background;
}

.marker.active {
  background: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <a id="link1">Link 1</a>
  <a id="link2">Link 2</a>
  <a id="link3">Link 3</a>
</div>

<div>
  <div class="marker" id="marker1">Marker 1</div>
  <div class="marker" id="marker2">Marker 2</div>
  <div class="marker" id="marker3">Marker 3</div>
</div>
bkhjykvo

bkhjykvo2#

如果你不能改变你的html,你可以使用属性starts with selector和eq来添加一个类到相应的标记:

const $markers = $('[id^="marker"]');

$('[id^="link"]').each((index, link) => {
   const $marker = $markers.eq(index); // get corresponding marker
   
   $(link).on('mouseenter', () => {
     $marker.addClass('background');
   }).on('mouseleave', () => {
     $marker.removeClass('background');
   });
});
.background {
  background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <a id="link1">Link 1</a>
  <a id="link2">Link 2</a>
  <a id="link3">Link 3</a>
</div>

<div>
  <div id="marker1">Marker 1</div>
  <div id="marker2">Marker 2</div>
  <div id="marker3">Marker 3</div>
</div>

相关问题