【发布时间】:2021-07-23 09:40:51
【问题描述】:
我在我的代码中写了两次这个 HTML 代码:
<a class="button-to-hover">LEARN MORE</a>
<div class="buttons"></div>
我想做的是让“.buttons”
【问题讨论】:
-
为什么你所有的函数不用的时候都有参数?
标签: javascript arrays function error-handling
我在我的代码中写了两次这个 HTML 代码:
<a class="button-to-hover">LEARN MORE</a>
<div class="buttons"></div>
我想做的是让“.buttons”
【问题讨论】:
标签: javascript arrays function error-handling
this 访问器在这里是错误的。
这是修复this 问题后的解决方案:
function appearUnderline(underline) {
underline.style.visibility = "visible"; // make the div visible
}
function disappearUnderline(underline) {
underline.style.visibility = "hidden"; // make the div invisible (for when the user stops hovering over the element)
}
function buttonHover(button) {
button.onmouseover = appearUnderline(this.nextSibling); // when the user hovers, appear the sibling of the element
button.onmouseout = disappearUnderline(this.nextSibling); // when the user stops hovering, disappear the sibling of the element
}
let buttonNumberOne = document.getElementsByClassName('button-to-hover')[0]; // take the first element you can hover in
let buttonNumberTwo = document.getElementsByClassName('button-to-hover')[1]; // take the second element you can hover in
let button1 = buttonHover(buttonNumberOne); // apply the first button as an argument in buttonHover() function
let button2 = buttonHover(buttonNumberTwo); // apply the second button as an argument in buttonHover() function
您还需要添加检查以确保传递的 nextSibling 不为空。
这里有一个更简单的解决方案:
var buttonToHover = document.getElementsByClassName("button-to-hover")[0];
var buttons = document.getElementsByClassName("buttons")[0];
buttonToHover.onmouseover = () => {
buttons.style.visibility = "visible";
}
buttonToHover.onmouseout = () => {
buttons.style.visibility = "hidden";
}
.buttons {
visibility: hidden;
}
<a class="button-to-hover">LEARN MORE</a>
<div class="buttons">test</div>
如果您想用this 解决这个问题,bind 的概念可以为您提供更多帮助。
【讨论】:
采用 CyberDev 的答案并使其更加灵活并使用现代 javascript(如果您想支持旧版本的浏览器,请将 querySelectorAll 替换为 getElementsByClassName 并循环它):
//Select all your buttons to hover and loop over the list
//With querySelector or querySelectorAll you select elements with css selectors (start with . for a class and # for an id etc)
document.querySelectorAll(".button-to-hover").forEach((btn)=> {
//Add the action to perform when the mouse is over the button
btn.addEventListener('mouseover', ()=> {
btn.nextElementSibling.style.visibility = "visible";
});
//Add the action to perform when the mouse is not over the button anymore
btn.addEventListener('mouseout', ()=> {
btn.nextElementSibling.style.visibility = "hidden";
});
});
.buttons {
visibility: hidden;
}
<a class="button-to-hover">LEARN MORE</a>
<div class="buttons">content 1</div>
<div><!--Your page content--></div>
<a class="button-to-hover">LEARN MORE</a>
<div class="buttons">content 2</div>
【讨论】: