Keydown 中 DIV 中的滚动文本
Scrolling Text in DIV on Keydown
我想在 div
上创建滚动效果,这样当按下 SPACE
键时,第一个 span
向上移出可见范围,而 span
变得可见。
HTML
<div class="scroll-div">
<span class="item1">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Rerum, beatae.</span>
<span class="item1">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Rerum, beatae.</span>
<span class="item1">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Rerum, beatae.</span>
<span class="item1">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Rerum, beatae.</span>
</div>
CSS
.scroll-div{
width: 150px;
height: 100px;
overflow-y: scroll;
}
JS
const scrollDiv = document.querySelector('.scroll-div');
scrollDiv.addEventListener('keydown', event => {
if(event.key == ' '){
...scroll up;
}
})
PS:如果单独使用CSS就可以完成,我更愿意。
您必须在每个 .
的末尾使用
/* Your Modified Javascript */
<script language="javascript">
//Get the no of elements having the same classname.
var items = document.getElementsByClassName("item1").length;
i=0; //set a variable to get the current element.
const scrollDiv = document.querySelector('.scroll-div');
scrollDiv.addEventListener('keydown', event => {
if(event.key == ' '){
//Scroll to each element on every key press
document.getElementsByClassName("item1")[i].scrollIntoView({behavior: "smooth"});
i++; //Increment the value of i to jump to next <span>
}
});
</script>
希望此代码能解决您的问题
我想在 div
上创建滚动效果,这样当按下 SPACE
键时,第一个 span
向上移出可见范围,而 span
变得可见。
HTML
<div class="scroll-div">
<span class="item1">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Rerum, beatae.</span>
<span class="item1">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Rerum, beatae.</span>
<span class="item1">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Rerum, beatae.</span>
<span class="item1">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Rerum, beatae.</span>
</div>
CSS
.scroll-div{
width: 150px;
height: 100px;
overflow-y: scroll;
}
JS
const scrollDiv = document.querySelector('.scroll-div');
scrollDiv.addEventListener('keydown', event => {
if(event.key == ' '){
...scroll up;
}
})
PS:如果单独使用CSS就可以完成,我更愿意。
您必须在每个 .
的末尾使用/* Your Modified Javascript */
<script language="javascript">
//Get the no of elements having the same classname.
var items = document.getElementsByClassName("item1").length;
i=0; //set a variable to get the current element.
const scrollDiv = document.querySelector('.scroll-div');
scrollDiv.addEventListener('keydown', event => {
if(event.key == ' '){
//Scroll to each element on every key press
document.getElementsByClassName("item1")[i].scrollIntoView({behavior: "smooth"});
i++; //Increment the value of i to jump to next <span>
}
});
</script>
希望此代码能解决您的问题