简体   繁体   中英

How can I create a draggable scrollbar that manipulates the viewport using javascript?

I'm trying to create a web page that has a slider at the bottom of the page, that can be dragged from left to right to shift the viewport. I've tried to draw a simple diagram of what I'm trying to achieve here:

在此处输入图片说明

The red box is the draggable slider. The user should be able to drag this red box from side to side and this should correspond with the image in the main viewport. Are there any plugins available for this?

At the moment I'm considering using the jquery-ui draggable plugin to handle the slider, but I'm not sure how to manipulate the viewport?

I'm thinking that maybe I could capture the distance moved by the slider and then apply a multiplier to that value to get the move the viewport by the correct amount but I'm not sure if this is a sensible idea?

What would be the best way to achieve this?

Thanks

You could start from the jQuery UI slider for the scroll bar at the bottom.

Modify it to fit your needs (little bit of css tweaking)

With the $('.viewport')[0].scrollLeft = xpos method you can scroll to the right x position.

Here is an example: http://jsfiddle.net/Vandeplas/zAJtL/

js:

var percentage = 50;

$('.scrollTo').click(function(){
    var vp = $('.viewport')[0];
        vp.scrollLeft = (percentage / 100) * vp.scrollWidth;
    console.log(vp.scrollWidth);
});

css:

.viewport {
    width: 200px;
    height: 40px;
    overflow: auto; /* set to hidden to hide the default scrollbar*/
}

html:

<div class="viewport"> azertyqwertyazertyqwertyazertyqwertyazertyqwertyazertyqwertyazertyqwertyazertyqwertyazertyqwertyazertyqwertyazertyqwertyazertyqwertyazertyqwertyazertyqwertyazertyqwertyazertyqwertyazertyqwertyazertyqwertyazertyqwertyazertyqwertyazertyqwertyazertyqwertyazertyqwertyazertyqwertyazertyqwertyazertyqwertyazertyqwertyazertyqwertyazertyqwertyazertyqwertyazertyqwertyazertyqwertyazertyqwertyazertyqwertyazertyqwertyazertyqwertyazertyqwertyazertyqwertyazertyqwertyazertyqwertyazertyqwertyazertyqwerty </div>
<input class="scrollTo" type="button" value="scroll"/>

UPDATE: With slider: http://jsfiddle.net/Vandeplas/zAJtL/1/

In case anyone was wondering, I managed to find the solution using this as a base: http://jeffschuette.com/2011/05/02/jquery-ui-slider-tutorial/

Hopefully it'll help anyone else trying to achieve the same thing!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM