gpt4 book ai didi

javascript - 如何在没有 jQuery 的情况下切换Class()

转载 作者:行者123 更新时间:2023-12-03 12:09:03 27 4
gpt4 key购买 nike

这是我到目前为止所拥有的:

function highlighton(id1, id2) {
document.getElementById(id1).classList.add('highlight');
document.getElementById(id2).classList.add('highlight');
}

function highlightoff(id1, id2) {
document.getElementById(id1).classList.remove('highlight');
document.getElementById(id2).classList.remove('highlight');
}

HTML 代码:

<span id="f000020" onmouseover="highlighton('f000020', 'f000020t')" onmouseout="highlightoff('f000020', 'f000020t')">It is impossible to say how first the idea entered my brain;</span>

<span id="f000020t" onmouseover="highlighton('f000020', 'f000020t')" onmouseout="highlightoff('f000020', 'f000020t')">Es imposible decir cómo es que por vez primera la idea entró a mi cerebro;</span>

JSFiddle以供进一步引用。

这个想法是,如果您将鼠标悬停在英语 ID 范围或西类牙语 ID 范围上,它会同时更改两者的背景。对于不引人注目的要求,它必须切换类,并且对于特定的构建限制,它不能使用 jQuery。

最佳答案

在这种特殊情况下,您可能不需要 .toggleClass() 因为您想确保当鼠标移出时删除一个类;某些奇怪的边缘情况不太可能会破坏切换状态。

function highlighton(id1, id2) {
document.getElementById(id1).classList.add("highlight");
document.getElementById(id2).classList.add("highlight");
}

function highlightoff(id1, id2) {
document.getElementById(id1).classList.remove("highlight");
document.getElementById(id2).classList.remove("highlight");
}

确保这些函数是在全局范围内定义的,否则您无法在内联 JavaScript 中使用它们。更好的是使用 .addEventListener() 从代码注册事件处理程序(不过,请注意使用 .attachEvent() 的 IE < 9 浏览器)

Demo

关于javascript - 如何在没有 jQuery 的情况下切换Class(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25049575/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com