简体   繁体   中英

positioning a div when dragging

I have this fiddle: http://jsfiddle.net/eDyHf/1/

$("#ninjaimage1").draggable({
    containment: "#cirlce1",
    stop: function (event, ui) {
        $("#cirlce1").animate({
            top: $(this).offset().top,
            left: $(this).offset().left
        });
    }
}); 

my question is that when I drag the image inside the div I want the image stay always in the center of the div how can I achieve this

is that what you are looking for? (otherwise you must provide a more precise explanation of your problem!)

http://jsfiddle.net/u4CBW/

simply add +60 to the values to change the circle position correctly:

$("#cirlce1").animate({ top: $(this).offset().top-60, left: $(this).offset().left-60 });

why don't you add the two divs inside each other and only append the drag event to the outer (circle)? then it will always stay in the center, without big effort in javascript, like so:

http://jsfiddle.net/2ebnz/

HTML:

<div id="field">
    <div id="cirlce1" class="circlle">
        <img id="ninjaimage1" class="Ninjaimg" src="http://www.boursematch.com/assets/images/avatar_default.gif"></img>
    </div>
</div>

CSS:

.Ninjaimg {
        position:relative;
        margin-top: 60px;
        margin-left: 60px;
        width:30px;
        height:30px;
        display:block;
        cursor:pointer;
        z-index:3000;
    }
    .circlle {
        position: absolute;
        width: 150px;
        height: 150px;
        -moz-border-radius: 50%;
        border-radius: 50%;
        border:1px solid black;
        position: absolute;
        z-index:1;
        display:block;
    }

JS:

 $(document).ready(function () {
            $("#cirlce1").draggable();
        });

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