Javascript滚动到动态元素

时间:2014-08-19 17:11:32

标签: javascript html css

我正在使用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>

1 个答案:

答案 0 :(得分:1)

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。