Получение идентификаторов элементов при наведении курсора мыши

#javascript #jquery #animation #events #jquery-animate

#javascript #jquery #Анимация #Мероприятия #jquery-анимировать

Вопрос:

Было бы неплохо, если бы кто-нибудь мог помочь. Я создал анимированное меню. Единственное, что в моем JS я повторяю свой код для всех пяти кнопок. Я пытался получить идентификаторы из каждого элемента html, чтобы оптимизировать свой скрипт, но это не работает. Пожалуйста, помогите. Вот мой код:

 <!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <script type="text/javascript" src="html/js/jquery.js"></script>
    <script type="text/javascript" src="jquery-ui.min.js"></script>
    <script type="text/javascript" src="menu.js"></script>
    <link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
    <nav>
        <div class="button-container">
            <a id="link-1" class="link" onclick="location='page1.html'; return false" href="http://Buttonname1">
                <!-- Image apparaissant au clic -->
                <img id="bottom-1-clicked" class="toggle-1" src="button58.gif">
                <!-- Image apparaissant au survol après disparition de l'image d'origine -->
                <img id="bottom-1" class="toggle-1" src="button59.gif">
                <!-- Image apparaissant au chargement de la page. Glisse vers la droite au survol puiq revient vers la gauche -->
                <img id="top-1" class="toggle-1" src="button55.gif">
                <span class="text-container">Buttonname1</span>
            </a>
        </div>
        <div class="button-container">
            <a id="link-2" class="link" onclick="location='page2.html'; return false" href="http://Buttonname2">
                <img id="bottom-2-clicked" class="toggle-2" src="button58.gif" alt="">
                <img id="bottom-2" class="toggle-2" src="button59.gif" alt="">
                <img id="top-2" class="toggle-2" src="button55.gif" alt="">
                <span class="text-container">Buttonname2</span>
            </a>
        </div>      
    </nav>
</body>
</html>
 

Вот мой JS:

     $(document).ready(function(){
        setInterval(function() { 
        $('.link').hover(function(childs) {
            // Hovering the menu item, the first image slides to the right, discovering another image
            $(this.id).hover(function(){
                $(":nth-child(3)", this).attr('id').stop(true, false).animate({ left: 130 }, 300);
            });
            // On mouse leave, the image slides back to the left
            $(this.id).mouseleave(function(){
                $(":nth-child(3)", this).attr('id').stop(true, false).animate({ left: 0 }, 300);
            });
            // On click, the image changes, displaying a third image
            $(this.id).mousedown(function(){
                $(":nth-child(2)", this).attr('id').hide(50);
                $(":nth-child(1)", this).attr('id').show(50);
            });
        });
    }, 300 );
});
 

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

1. Вы должны писать свои комментарии на английском языке, чтобы больше людей поняли

2. Ваш код кажется очень запутанным. Каждые 300 мс вы привязываете другой hover обработчик событий, который сам по себе имеет 3 других обработчика событий, включая другой hover обработчик. Я не совсем уверен, какова ваша цель, но я могу сказать вам, что логика прямо сейчас неверна, и что ваш запрос на получение id элемента не имеет отношения к делу, поскольку код должен быть написан не так. Не могли бы вы отредактировать вопрос, включив в него все соответствующие HTML и CSS, а также описание вашей цели.

3. Расширяя комментарии Рори, using $(this.id) не указывает "#" префикс, необходимый для селектора идентификаторов, и эквивалентен $('link-1') тому, который ищет элемент <link-1></link-1> . Ваш код полон проблем

4. Сделайте код доступным для выполнения в виде фрагмента кода.

Ответ №1:

Во-первых, извините за комментарии, я не знал, что они есть на французском, я изменил их.

Вот как работает мой скрипт: кнопки содержат 3 изображения. Первый появляется при загрузке страницы. При наведении курсора мыши он перемещается вправо, открывая второе изображение. Здесь, когда мышь покидает кнопку, первые изображения возвращаются назад, сдвигаясь влево, или при нажатии на кнопку второе изображение исчезает, обнаруживая третье изображение.

При первом наведении указателя мыши определяется идентификатор кнопки.

Вот CSS:

 * {
    box-sizing: border-box;
}
nav {
    position: absolute;
    top: 0;
    left: 0;
    width: 130px;
    height: 194px;
    overflow: hidden;
}
.button-container {
    display: block;
    position: relative;
    height: 39px;
}   
.text-container {
    position: absolute;
    left: 0; right: 0;
    width: 100%;
    margin: auto;
    top: 50%;
    font: 12px arial;
    font-weight: bold;
    color: #990099;
    transform: translate(0, -65%);
    vertical-align: middle;
    text-align: center;
}       
.text-container:hover {
    color: #000000;
}
.text-container:active {
    color: #990099;
}
.toggle-1 {
    position: absolute;
    top: 0;
    left: 0;
}
.toggle-2 {
    position: absolute;
    top: 0;
    left: 0;
}
 

Ответ №2:

 $(document).ready(function() {
  $(".link").mouseover(function() {
    // Hovering the menu item, the first image slides to the right, discovering another image
    $(":nth-child(3)", this).stop(true, false).animate({
      left: 300
    }, {
      easing: "linear"
    }, 300);

    // On mouse leave, the image slides back to the left
    $("#"   this.id).mouseleave(function() {
      $(":nth-child(3)", this).stop(true, false).animate({
        left: 0
      }, {
        easing: "linear"
      }, 300);
    });

    // On click, the image changes, displaying a third image
    $("#"   this.id).mousedown(function() {
      $(":nth-child(2)", this).hide(50);
      $(":nth-child(1)", this).show(50);
    });
  });
}); 
 * {
  box-sizing: border-box;
}

nav {
  position: absolute;
  top: 0;
  left: 0;
  width: 130px;
  height: 194px;
  overflow: hidden;
}

.button-container {
  display: block;
  position: relative;
  height: 39px;
}

.text-container {
  position: absolute;
  left: 0;
  right: 0;
  width: 100%;
  margin: auto;
  top: 50%;
  font: 12px arial;
  font-weight: bold;
  color: #990099;
  transform: translate(0, -65%);
  vertical-align: middle;
  text-align: center;
}

.text-container:hover {
  color: #000000;
}

.text-container:active {
  color: #990099;
}

.toggle-1 {
  position: absolute;
  top: 0;
  left: 0;
}

.toggle-2 {
  position: absolute;
  top: 0;
  left: 0;
} 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="fr">

<head>
  <meta charset="UTF-8">
  <script type="text/javascript" src="menu.js"></script>
  <link rel="stylesheet" href="style.css" type="text/css" />
</head>

<body>
  <nav>
    <div class="button-container">
      <a id="link-1" class="link" onclick="location='page1.html'; return false" href="http://Buttonname1">
        <!-- Image appearing on click -->
        <img id="bottom-1-clicked" class="toggle-1" src="[button58.gif][1]">
        <!-- Image appearing on hover, after the upper one disappears -->
        <img id="bottom-1" class="toggle-1" src="[button59.gif][1]">
        <!-- Image appearing when the page is loaded. The images slides to the right on  hover and slides to the left when mouse leaves it -->
        <img id="top-1" class="toggle-1" src="[button55.gif][1]">
        <span class="text-container">Buttonname1</span>
      </a>
    </div>
    <div class="button-container">
      <a id="link-2" class="link" onclick="location='page2.html'; return false" href="http://Buttonname2">
        <img id="bottom-2-clicked" class="toggle-2" src="[button58.gif][1]" alt="">
        <img id="bottom-2" class="toggle-2" src="[button59.gif][1]" alt="">
        <img id="top-2" class="toggle-2" src="[button55.gif][1]" alt="">
        <span class="text-container">Buttonname2</span>
      </a>
    </div>
  </nav>
</body>

</html> 

Я нашел решение. Это только одна проблема. При нажатии кнопки изображение меняется и открывается новая страница. Но, когда мы возвращаемся на предыдущую страницу, нажимая кнопку браузера, кнопка не возвращается в исходное состояние. Это означает, что когда верхнее изображение сдвигается вправо, оно отображает изображение, которое обычно отображается при щелчке, вместо того, которое отображается при наведении курсора мыши.

Вот мой новый скрипт:

 $(document).ready(function(){
        $(".link").mouseover(function() {
            // Hovering the menu item, the first image slides to the right, discovering another image
            $(":nth-child(3)", this).stop(true, false).animate({ left: 300 }, { easing: "linear" }, 300);
            
            // On mouse leave, the image slides back to the left
            $("#" this.id).mouseleave(function(){
                $(":nth-child(3)", this).stop(true, false).animate({ left: 0 }, { easing: "linear" }, 300);
            });
        
             // On click, the image changes, displaying a third image
            $("#" this.id).mousedown(function(){
                $(":nth-child(2)", this).hide(50);
                $(":nth-child(1)", this).show(50);
            });
        });
});