通过滚动移动DIV [英] Moving a DIV by scrolling

查看:61
本文介绍了通过滚动移动DIV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个jQuery滚动条,用于滚动< div>中的内容.类似于 jQuery ScrollPane .

I'm creating a jQuery scrollbar which scrolls the content in a <div>. It's something like jQuery ScrollPane.

我已经到了需要移动滚动按钮的地步.我的问题是:没有任何UI插件的最佳方法是什么?因此,当用户单击滚动按钮时,可以通过mousedown事件在其父容器中垂直移动它.我该怎么办?

I've come to the point where I need to move the scroll button. My question is: what is the best way to do it without any UI plugin? So when the user clicks on the scroll button it can be moved vertically in its parent container with a mousedown event. How could I do that?

推荐答案

这是一个起点,希望这是您追求的目标:

Here's a starting point, hope that's what you're after:

$(function() {
    $('.slider').slider();
});

$.fn.slider = function() {
    return this.each(function() {
        var $el = $(this);
        $el.css('top', 0);
        var dragging = false;
        var startY = 0;
        var startT = 0;
        $el.mousedown(function(ev) {
            dragging = true;
            startY = ev.clientY;
            startT = $el.css('top');
        });
        $(window).mousemove(function(ev) {
            if (dragging) {
                // calculate new top
                var newTop = parseInt(startT) + (ev.clientY - startY);
                
                //stay in parent
                var maxTop =  $el.parent().height()-$el.height();          
                newTop = newTop<0?0:newTop>maxTop?maxTop:newTop;
                $el.css('top', newTop );
            }
        }).mouseup(function() {
            dragging = false;
        });
    });
}

.container{
    position:relative;
    border:1px solid red;
    height:100px;
}
.slider{
    height:20px;
    width:20px;
    background:green; 
    position:absolute;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <div class="container">
    <div class="slider" />
  </div>
</div>
<br/>
<div class="container">
  <div class="slider" />
</div>

这篇关于通过滚动移动DIV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆