Skip to content
TheChatArchiveThe Chat Archive
gpt-4-turbo-2024-04-09· OpenAIAi2 WildChat-4.8M (AI2)

мне нужно написать скрипт на js. у меня есть 6 строчек текста. каждая строчка имеет…

  1. User

    мне нужно написать скрипт на js. у меня есть 6 строчек текста. каждая строчка имеет класс text. к каждой строчке относится картинка. у каждой картинки класс img с цифрами от 0 до 5. по умолчанию активна первая строчка и картинка которая относится к ней img0. у строчки opacity 100%. у не активных строчек opacity 40%. при наведение курсора на другую строчку должна меняться картинка и изменяться opacity

  2. Assistant

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

    1. Определите HTML-структуру с текстовыми элементами и картинками.
    2. Примените CSS для установки начальных стилей.
    3. Используйте JavaScript для добавления обработчиков событий на элементы.

    Вот пример кода, который можно использовать:

    HTML

    <div class="container">
      <div class="text" data-index="0">Текст 1</div>
      <div class="text" data-index="1">Текст 2</div>
      <div class="text" data-index="2">Текст 3</div>
      <div class="text" data-index="3">Текст 4</div>
      <div class="text" data-index="4">Текст 5</div>
      <div class="text" data-index="5">Текст 6</div>
    </div>
    <div class="images">
      <img class="img img0" src="path/to/image0.jpg" style="opacity: 1;" alt="Image 0">
      <img class="img img1" src="path/to/image1.jpg" style="opacity: 0;" alt="Image 1">
      <img class="img img2" src="path/to/image2.jpg" style="opacity: 0;" alt="Image 2">
      <img class="img img3" src="path/to/image3.jpg" style="opacity: 0;" alt="Image 3">
      <img class="img img4" src="path/to/image4.jpg" style="opacity: 0;" alt="Image 4">
      <img class="img img5" src="path/to/image5.jpg" style="opacity: 0;" alt="Image 5">
    </div>
    

    CSS

    .text {
      opacity: 0.4;
      cursor: pointer;
    }
    
    .text.active {
      opacity: 1;
    }
    
    .img {
      display: none; /* Изначально скрыты, кроме активного */
      transition: opacity 0.3s;
    }
    
    .img.active {
      display: block;
      opacity: 1;
    }
    

    JavaScript

    document.addEventListener("DOMContentLoaded", function() {
      const texts = document.querySelectorAll('.text');
      const images = document.querySelectorAll('.img');
    
      texts.forEach(text => {
        text.addEventListener('mouseover', function() {
          const index = this.getAttribute('data-index');
    
          // Update texts opacity
          texts.forEach(t => t.classList.remove('active'));
          this.classList.add('active');
    
          // Show the correct image
          images.forEach(img => {
            img.style.display = 'none';
            img.style.opacity = 0;
          });
          const activeImg = document.querySelector('.img' + index);
          activeImg.style.display = 'block';
          setTimeout(() => { activeImg.style.opacity = 1; }, 100); // delay for smooth transition
        });
      });
    
      // Set initial active elements
      texts[0].classList.add('active');
      images[0].style.display = 'block';
      setTimeout(() => { images[0].style.opacity = 1; }, 100);
    });
    

    Здесь используется data-index чтобы сопоставить текст с соответствующей картинкой. Мы также использовали mouseover вместо mouseenter, потому что он более общий и срабатывает каждый раз, когда курсор переходит на элемент или его дочерние элементы.

    Этот скрипт делает первую строку и первую картинку активными по умолчанию, а затем изменяет прозрачность и картинку при наведении на другие строки.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.