Что я делаю неправильно, и у меня есть ошибка типа: Не удается установить свойство «видимость» неопределенного?

#javascript #arrays #function #error-handling

Вопрос:

Я написал этот HTML-код дважды в своем коде:

 <a class="button-to-hover">LEARN MORE</a>
<div class="buttons"></div>
 

Что я хотел сделать, так это заставить «.кнопки» <div> появляться всякий раз, когда кто-то наводит курсор на элемент «.кнопка для наведения» <div><a>. Итак, я также добавил этот CSS-код:

 .buttons {
   visibility: hidden;
}
 

Наконец, я добавил этот код Javascipt:

 function appearUnderline(underline) {
    this.style.visibility = "visible"; // make the div visible
}

function disappearUnderline(underline) {
    this.style.visibility = "hidden"; // make the div invisible (for when the user stops hovering over the element)
}

function buttonHover(button) {
    this.onmouseover = appearUnderline(this.nextSibling); // when the user hovers, appear the sibling of the element
    this.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
 

Как вы можете видеть, я новичок в Javascript. Этот код не работает. Что я делаю не так?

Комментарии:

1. Почему у всех ваших функций есть параметр, если они его не используют?

Ответ №1:

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 помощью .

Ответ №2:

Принимая ответ 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>