簡體   English   中英

可在左側和頂部拖動 %

[英]Draggable in left and top %

 $(function() { $('.dragElement').draggable({ containment: "parent" }).filter('.dragElement').draggable("option", "axis"); });
 .one { width: 500px; height: 500px; border: 2px solid; } .dragElement { width: 50px; height: 50px; border: 5px solid white; box-shadow: rgba(0, 0, 0, 0.5) 0px 0px 10px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="//ajax.aspnetcdn.com/ajax/jquery.ui/1.10.3/jquery-ui.min.js"></script> <div class="one"> <div class="dragElement"> </div> </div>

請告訴我,有沒有這樣的代碼。 當你移動一個元素時, lefttoppx書寫。 如何使此位置以相對於父級的%記錄。

首先,您可以獲得父級的高度和寬度(您也可以在調整窗口大小時使用事件重新計算它們)。

然后,使用drag方法獲取位置的lefttop ,您可以使用函數將其轉換為使用當前位置和父高度或寬度的百分比。

 $(function() { $('.dragElement').draggable({ containment: "parent", drag: function(event, ui) { console.log( "top: " + calcPerc(parentHeight, ui.position.top), "left: " + calcPerc(parentWidth, ui.position.left) ); } }).filter('.dragElement').draggable("option", "axis"); function calcPerc(par, child) { return (100*child)/par; } }); var parentEl = $(".one"); var parentHeight, parentWidth; window.addEventListener('resize', recalcParent); function recalcParent() { parentHeight = parseInt(parentEl.css('height')); parentWidth = parseInt(parentEl.css('width')); } recalcParent();
 .one { width: 500px; height: 500px; border: 2px solid; } .dragElement { width: 50px; height: 50px; border: 5px solid white; box-shadow: rgba(0, 0, 0, 0.5) 0px 0px 10px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="//ajax.aspnetcdn.com/ajax/jquery.ui/1.10.3/jquery-ui.min.js"></script> <div class="one"> <div class="dragElement"> </div> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM