如何为自定义滚动元素添加限制?

时间:2011-09-29 04:47:59

标签: javascript jquery html css

我在一个容器中显示了一个非常大的图像,图像在调整大小时随着视图端口延伸,但是由于图像太大,我在页面的上方和下方添加了滚动按钮,我现在唯一的问题是,当我向上或向下按压没有限制时,用户可以继续前进,直到图像完全看不见,我怎么能阻止这种情况发生?

这是我到目前为止的代码,

HTML:

<body>
    <div id="wrapper">  

        <div class="scroll top"></div> 

        <div id="content">

            <div id="zoom_container">

                <img id="image" src="8052x2000px" />

            </div>

        </div>

        <div class="scroll bot"></div>

    </div>

</body>

CSS:

body {
   width: 100%;
   height: 100%;
   margin: 0;
   padding: 0;
}

#wrapper {
   overflow: hidden;
   height: 100%;
   max-height: 100%;
}

#content {
   min-height: 100% !important;
   height: 100%;
   width: 100%;
   margin: 0;
   padding: 0;
}

#image {
   position: fixed;
   top: 0;
   left: 0;
   width: 100%;
}

jQuery的:

//side scroller bar
$('.scroll').live('click', function(){

    var direction = $(this).hasClass('top');
    var img_pos_top = $("#zoom_container img").position().top;
    var inc = 0;

    inc = $("#zoom_container img").height() / 10;

    if(direction)
    {

        inc = $("#zoom_container img").position().top + inc;

    }
        else
    {
        inc = $("#zoom_container img").position().top - inc;
    }

    $("#zoom_container img").css({ position: 'relative',top: inc });

});

所以你可以看到我每次点击增加或减少图像顶部定位10%的高度,我怎样才能确保图像的顶部永远不会比视口的顶部更低图像的底部是否永远不会超过视口的底部?

是否有更好的更有效的方法来实现相同的结果?

1 个答案:

答案 0 :(得分:0)

试试这个。

<html>
<head>
    <title>Canvas Sizing</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
    <script type="text/javascript">
        $(function() {

            var canvasContext;
            resizeCanvas();
            $(window).resize(function() { resizeCanvas() });

            function resizeCanvas()
            {
                var w = window.innerWidth - 40;
                var h = window.innerHeight - 40;
                var canvasString = '<canvas id="mainCanvas" width="' + w + '" height="' + h + '">Canvas is not supported</canvas>';             

                $('#contentholder').empty();
                $(canvasString).appendTo('#contentholder');
                canvasContext = $('#mainCanvas').get(0).getContext('2d');               

                drawOnCanvas();
            }

            function drawOnCanvas()
            {
                var x = 15;
                var y = 35;

                canvasContext.font = "30pt serif";
                canvasContext.fillStyle="#0f0";
                canvasContext.fillText("Hello World!", x, y);
            }
        });
        </script>
<style>
  #mainCanvas
  {
    background-color: #000;
    border: solid 3px #0F0;
  }
  body
  {
    background: #000;
  }
  #contentholder
  {
    width: 99%;
    height: 99%;
    margin: auto;
  }
 </style
</head>

<body>
    <div id="contentholder"></div>
</body>