如何在html中具有多个连接的其他地方悬停文本时更改文本样式
Posted
技术标签:
【中文标题】如何在html中具有多个连接的其他地方悬停文本时更改文本样式【英文标题】:How to change text style when hovering over text elsewhere with multiple connections in html 【发布时间】:2021-10-03 23:25:42 【问题描述】:我是 html 新手,如果语法或其他内容有问题,请见谅。
我有一些 html 代码。当我将鼠标悬停在 1 上时,我希望句子“这是第一场比赛”改变例如稍后在文档中着色 我可以用这个 CSS 代码来实现:
#number1:hover ~ #match1
color: yellow;
#number2:hover ~ #match2
color: yellow;
Please hover over this number to see the respective match
<a id="number1">1</a>
<br>
Or hover over this number to see the respective match
<a id="number2">2</a>
<br>
<a id="match1">This is the first match</a>
<br>
<a id="match2">This is the second match</a>
但是,我有 多个 连接,我想要相同的模式,而不仅仅是这两个。有什么方法可以在文档中全局轻松地应用这种模式?
我不知道<a>
是否正确使用,但我认为href
可能是一个解决方案,但我不确定。
提前致谢!
【问题讨论】:
因为它不是一个真正的链接,<span>
将是正确的标签。 CSS 可以由 javascript 动态生成。但为什么?你需要多少这样的连接?在 CSS 文件中有 100 行比在 JavaScript 中构建要好得多。
而不是匹配的 id,您可以使用一个名为 id 的类,它应该与之匹配,因此如果您有超过 1 个匹配项,您可以多次重复使用该类。 (我希望这很清楚)
@Samuel,好的,谢谢!然后我会手动写下连接,如果这样更好:-) @G-Cyrillus,谢谢!我不确定这将如何使每次我有连接时都不必写这个:? ``` #number1:hover ~ #match1 颜色:黄色; ```
【参考方案1】:
您可以使用带有 onmouseover(悬停)事件的 Javascript 来解决这个问题。然而,为了给所有我们想要的标签赋予相同的属性,我们需要给它们一个共同的类名。
<body>
<a class = "colorchange" id="match1">This is the first match</a>
<br>
<a class = "colorchange" id="match2">This is the second match</a>
<br>
<a class = "colorchange" id="match3">This is the third match</a>
<br>
<a class = "colorchange" id="match4">This is the fourth match</a>
<script>
elements = document.getElementsByClassName("colorchange");
for(var i = 0, length = elements.length; i < length; i++)
colorChange(elements[i])
function colorChange(btn)
btn.onmouseover = function()
btn.style.color = "yellow"
</script>
</body>
【讨论】:
以上是关于如何在html中具有多个连接的其他地方悬停文本时更改文本样式的主要内容,如果未能解决你的问题,请参考以下文章