javascript - 悬停时 HTML 突出显示标签

标签 javascript html css tags

给定以下 html:

This is a test to
<cpos data-idcpos="10" data-comment="1"> 
  highlight only this portion of text 
</cpos> and not this

我的任务是只突出显示 cpos 部分。我可以自己突出显示一个 div 类,但对如何执行此操作有点困惑。我正在使用 javascript 以及 css 样式

如有任何帮助,我们将不胜感激。谢谢!

最佳答案

无需javascript,只需使用css :hover

cpos:hover{
  background:yellow;
  }
This is a test to<cpos data-idcpos="10" data-comment="1"> highlight only this portion of text </cpos> and not this

更新

If I had multiple cpos tags with different ids and wanted to highlight an individual one on hover

只需使用 #

定位每个单独的 id

#MyId:hover{
  background:yellow;
  }
This is a test to<cpos data-idcpos="10" data-comment="1"> highlight only this portion of text </cpos> and not this

This is a test to<cpos id="MyId" data-idcpos="10" data-comment="1"> highlight only this portion of text </cpos> and not this

Also, is there anyway you could show me how to do this using javascirpt?

使用onmouseoveronmouseout 事件

This is a test to<cpos data-idcpos="10" data-comment="1" onmouseover="this.style.background='yellow'" onmouseout="this.style.background=''"> highlight only this portion of text </cpos> and not this

Is there a way to do it similarly to your javascript example but without changing the cpos tag attributes?

是的,遍历它们并以编程方式附加

var elements = document.getElementsByTagName('cpos');
for(var i = 0; i < elements.length; i++){
  elements[i].onmouseover = function(){
    this.style.background = 'yellow';
    }
  elements[i].onmouseout = function(){
    this.style.background = '';
    }
  }
This is a test to
<cpos data-idcpos="10" data-comment="1">
  highlight only this portion of text
</cpos>and not this This is a test to
<cpos data-idcpos="10" data-comment="1">
  highlight only this portion of text
</cpos>and not this This is a test to
<cpos data-idcpos="10" data-comment="1">
  highlight only this portion of text
</cpos>and not this

关于javascript - 悬停时 HTML 突出显示标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30670346/

相关文章:

javascript - YouTube 视频在 iPhone 的 Safari 或 UIWebView 上自动播放

javascript - 字数限制或内容高度限制,多看少

html - 如果指定了高度,如何自动调整div的高度?

javascript - JS - array[index].length 读取为未定义,即使它在函数中打印

javascript - JS/MongoDB : How to get count() value of collection?

javascript - 带 react 的 Jest/ enzyme - "Target container is not a DOM element."

javascript - 在 HTML 中内联 ECMAScript 模块

html - Div 边框和定位

javascript - $scope.$watch(var,function) undefined 不是函数

javascript - 问题淡出选择器