You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据内部HTML内容获取目标div的id?及背景色设置问题

解决方法:根据文本内容获取目标元素ID并设置背景色

一、初始问题:获取包含指定文本的div的ID

你之前用parentNode只拿到父元素main的ID,是因为错误地定位到了文本节点的上层容器。其实直接定位到包含目标文本的.drawing元素,就能轻松拿到它的ID:

原生JavaScript方式

// 筛选出文本内容完全匹配的.drawing元素
const targetElement = Array.from(document.querySelectorAll('.drawing')).find(el => 
  el.textContent.trim() === 'IBC-CW1 -DE-02A'
);

if (targetElement) {
  console.log('目标元素ID:', targetElement.id); // 输出 hotspot1
}

jQuery方式

const $target = $('.drawing').filter(function() {
  return $(this).text().trim() === 'IBC-CW1 -DE-02A';
});

if ($target.length) {
  console.log('目标元素ID:', $target.attr('id')); // 输出 hotspot1
}

二、优化你的jQuery代码(设置背景色+滚动)

你提供的代码存在语法错误(var spot.hotspot_hover是无效的变量声明),而且可以简化逻辑,直接定位目标元素而非遍历所有.textLayer:

// 定义要匹配的目标文本
const hotspotHoverText = "IBC-CW1 -DE-02A";

// 先重置所有.drawing元素的背景色
$('.drawing').css('background-color', 'transparent');

// 找到包含目标文本的元素(如果需要精确匹配,把includes换成===即可)
const $targetSpot = $('.drawing').filter(function() {
  return $(this).text().trim().includes(hotspotHoverText);
});

if ($targetSpot.length) {
  // 给匹配到的元素设置背景色
  $targetSpot.css('background-color', '#ff0000');
  
  // 滚动到目标元素位置,调整偏移量
  $('#content-wrapper').animate({
    scrollTop: $targetSpot.offset().top + 300
  }, 'slow');
}

关键提示

  • 如果需要精确匹配文本(完全一致,包括空格),就把includes(hotspotHoverText)换成=== hotspotHoverText;如果只需要文本包含目标字符串,includes()会更灵活。
  • 直接筛选.drawing元素比遍历.textLayer再找父元素更高效,也更贴合你的HTML结构。

内容的提问来源于stack exchange,提问作者Vishnu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:53:47