Javascript 使用控件水平滚动图像的 div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5414304/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:06:27  来源:igfitidea点击:

scrolling a div of images horizontally with controls

javascriptjquery

提问by user520300

I have a div with a bunch of images in it. With arrow controls to the left and right. I want my div to scroll right and left through the images with the arrow controls. I can find vertically scrolling a div up and down but now left and right?

我有一个带有一堆图像的 div。左右箭头控制。我希望我的 div 使用箭头控件在图像中左右滚动。我可以找到垂直向上和向下滚动 div 但现在向左和向右滚动?

回答by Sean Adkinson

You can scroll left and right when clicking on your arrows by editing the scrollLeftDOM property of the scrolling element.

通过编辑scrollLeft滚动元素的DOM 属性,您可以在单击箭头时左右滚动。

Using jQuery, you can use the .scrollLeft()function to get or set the scrollLeftproperty - link to docs

使用 jQuery,您可以使用该.scrollLeft()函数来获取或设置scrollLeft属性 -文档链接

Here is a really simple page I just cooked up that shows the behavior:

这是我刚刚编写的一个非常简单的页面,它显示了行为:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>

<script type="text/javascript">
    function scrollDiv(dir, px) {
        var scroller = document.getElementById('scroller');
        if (dir == 'l') {
            scroller.scrollLeft -= px;
        }
        else if (dir == 'r') {
            scroller.scrollLeft += px;
        }
    }
</script>

<style type="text/css">
    #scroller {
        width: 400px;
        height: 400px;
        border: 1px solid blue;
        overflow: scroll;
        margin: 0 auto;
    }
    #inner-scroller {
        width: 800px;
        height: 800px;
    }
</style>

</head>
<body style="text-align: center;">

<a href="javascript: void(0);" onclick="scrollDiv('l', 20); return false;">scroll left</a>
|
<a href="javascript: void(0);" onclick="scrollDiv('r', 20); return false;"> scroll right</a>

<div id="scroller">
    <div id="inner-scroller">
        800x800
    </div>
</div>    
</body>
</html>