gpt4 book ai didi

Javascript滚动到动态元素

转载 作者:太空宇宙 更新时间:2023-11-04 13:01:57 25 4
gpt4 key购买 nike

我正在添加 ID 为“newid”的动态 div 元素并使用另一个按钮,我正在尝试滚动到该动态元素。添加几个动态元素后,当我按下滚动按钮时,我滚动到末尾(最后一个 div 元素)但它停止工作。我此测试的总体目标是滚动到动态添加的元素。我没有继续前进的基础知识,所以请有人帮助我朝着正确的方向前进。

下面是代码

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>

<body>
<button onclick="myfunction()">test</button> <button onclick="addElement()">Add Element</button>


<div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum odit, ipsa aspernatur reiciendis facere labore accusamus architecto perspiciatis minus ad perferendis, illo nisi doloribus id quidem corporis blanditiis vel itaque!</div>

<div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum odit, ipsa aspernatur reiciendis facere labore accusamus architecto perspiciatis minus ad perferendis, illo nisi doloribus id quidem corporis blanditiis vel itaque!</div>

<div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum odit, ipsa aspernatur reiciendis facere labore accusamus architecto perspiciatis minus ad perferendis, illo nisi doloribus id quidem corporis blanditiis vel itaque!</div>

<div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum odit, ipsa aspernatur reiciendis facere labore accusamus architecto perspiciatis minus ad perferendis, illo nisi doloribus id quidem corporis blanditiis vel itaque!</div>



<div id="demo">Test</div>

<script type="text/javascript">
function myfunction () {
document.getElementById('newid').scrollIntoView();
//alert("test");

}

function addElement() {
var element = document.createElement('div');
element.id = "newid";
document.body.appendChild(element);

element.appendChild(document.createTextNode
('New id'));
}

</script>
</body>
</html>

最佳答案

function myfunction ()  { 
var nodes = document.querySelectorAll('div.myclass');
nodes[nodes.length-1].scrollIntoView();
}

function addElement() {
var element = document.createElement('div');
element.className ='myclass';
element.appendChild(document.createTextNode('New div'));
document.body.appendChild(element);
}

无论我添加了多少,这段代码对我都有效。不需要 jQuery。

关于Javascript滚动到动态元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25389233/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com