在div内向下滚动到25px

时间:2015-04-21 13:39:24

标签: javascript jquery html css

我有一个可滚动的元素div#container。如何通过原生javascript将其向下滚动到25px?我的标记如下:

<div id = "container" style="overflow: auto;">
    <div class="filter-container" style="display: block;">
        <!-- content -->
    </div>
    <div class="filter-container" style="display: block;">
        <!-- content -->
    </div>
    <div class="filter-container" style="display: block;">
        <!-- content -->
    </div>
    <div class="filter-container" style="display: block;">
        <!-- content -->
    </div>
</div>

4 个答案:

答案 0 :(得分:1)

我认为您正在寻找Javascript Element.scrollLeft()Element.scrollTop()

在这里查找您需要的内容:w3schools DOM Element

答案 1 :(得分:1)

<head>
<script type="text/javascript">
    function Scroll () {
        var myCont = document.getElementById ("container");
        myCont.scrollLeft = 10;
        myCont.scrollTop = 40;
    }
</script>
</head> 
<body>

 <div id="container" style="overflow:scroll; width:150px; height:80px; white-space:nowrap background-color:#e0f0e0;">

     1. line with a long content <br />
     2. line with a long content <br />
     3. line with a long content <br />
     4. line with a long content <br />
     5. line with a long content <br />
     6. line with a long content <br />
     7. line with a long content <br />
     8. line with a long content <br />
     9. line with a long content <br />
</div>

    <button onclick="Scroll ();">Scroll the element above!</button>
</body>

答案 2 :(得分:1)

您可以使用

document.getElementById("container").scrollTop=25;

<强> DEMO

或者使用jQuery

$("#container").scrollTop(25);

答案 3 :(得分:1)

function scrollToElement(element) {    
    var positionX = 0,         
        positionY = 25;    

    while(element != null){        
        positionX += element.offsetLeft;        
        positionY += element.offsetTop;        
        element = element.offsetParent;        
        window.scrollTo(positionX, positionY);    
    }
}

var element = document.getElementById("container");
scrollToElement(element);
<div id = "container" style="overflow: auto;">
    <div class="filter-container" style="display: block;">
       test1
    </div>
    <div class="filter-container" style="display: block;">
      test2
    </div>
    <div class="filter-container" style="display: block;">
        ttest3
    </div>
    <div class="filter-container" style="display: block;">
        test4
    </div>
</div>

相关问题