简体   繁体   中英

Drag and drop to scroll position within HTML element using JavaScript (or jQuery)

I'd like to allow the user to drag and drop to a certain position inside of an HTML element (ie: DIV) relative to the current position, assuming the HTML element has content. I've only found examples where you can drag and drop an element within another element.

So basically I'd like to drag the browser window position to a different x/y location, similar to how Google Maps behaves. Although in my case, there is a height and width for the element, but I want to avoid showing a horizontal scroll bar and a vertical scroll bar. Is this possible with some JavaScript library? If so, can you point me to an example?

Edit

Noticing some strange things happening when you drag the rectangles across the screen.

Take this jFiddle..

http://jsfiddle.net/08p1dm0x/1/

..and add an external reference to:

//code.jquery.com/ui/1.11.1/jquery-ui.js

Then add this line..

$("#gfx_holder").draggable();

..to the on ready function:

$(function() {

This code should accomplish what you're looking for. It uses the jquery ui draggable extension to make elements draggable inside the "viewport". The overflow:hidden on the viewport prevents the scrollbar.

<!doctype html>
<html>
<head>
<title>Learning canvas</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>
<style>
   html, body, #viewPort
   {
    margin:0px;
    padding:0px;
    overflow:hidden;
    height:100%;
    width:100%;
   }
   #map
   {
    position:relative;
     height:1523px;
     width:3000px;
     background-image:url(http://www.mapplace.info/wp-content/uploads/2014/03/world-map-2.jpg);
   }
</style>
<script>
    $(document).ready(function()
    {
        $("#map").draggable();
    });
</script>
</head>
<body>
<div id="viewPort">
    <div id="map"/>
</div>

</body>
</html>

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