Как прокручивать каждый элемент в списке узлов один за другим в одной строке кода при нажатии клавиши?

У меня есть страница, на которой я хотел бы прокручивать каждый элемент в одной строке кода.

Код у меня есть до сих пор:

window.addEventListener("keyup", function (e) { e.keyCode==13 ?document.querySelectorAll("ins").scrollIntoView():void})

Я думал, что смогу заставить его работать с одним элементом, но я не получаю ключевые события (неважно, что это не скрипт в локальном файле):

window.addEventListener("keyup", function (e) { console.info("test") })

почему важна одна строка кода?

jonathan Heindl 06.04.2019 23:17

@jonathanHeindl Есть несколько причин и ограничений. Это может быть несколько строк. Основная причина заключается в предотвращении ошибок, если это имеет смысл.

1.21 gigawatts 06.04.2019 23:21

var current=0; function scrollIntoView(index){document.querySelectorAll("ins")[index‌​].scrollIntoView()}w‌​indow.addEventListen‌​er("keyup", function (e) { e.keyCode== 13 ? scrollIntoView(current++) :void })

jonathan Heindl 06.04.2019 23:26
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
1
3
328
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий
var current=0;
function scrollIntoView(index){
    let node=document.querySelectorAll("ins")[index];
    if (node){
         node.scrollIntoView();
     }
}
window.addEventListener("keyup", function (e) { 
      e.keyCode==13 ? scrollIntoView(current++) :void
});

не в одну строку:

var current=0;function scrollIntoView(index){let node=document.querySelectorAll("ins")[index];if (node){node.scrollIntoView();         }}window.addEventListener("keyup", function (e) { e.keyCode==13 ? scrollIntoView(current++) :void })

var current=0;

function scrollIntoView(index){
   let node=document.querySelectorAll("ins")[index];
   if (node){
       node.scrollIntoView();
   }
};

window.addEventListener("keyup", function (e) {
   current>=document.querySelectorAll("ins").length ? current = 0 : null;
   e.keyCode==13 && document.querySelectorAll("ins").length && scrollIntoView(current++);
});
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.<br>
<br>
<ins>first index</ins><br>
<br><br>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.<br><br><br>
<ins>second index</ins><br><br><br>
It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.<br><br><br>
<ins>third index</ins><br><br><br>
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.<br><br><br>

The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.<br><br><br>

There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text.

ах, хорошо, я не включил сравнение, если оно слишком высоко :on

jonathan Heindl 07.04.2019 01:12

Другие вопросы по теме