我正在嘗試計算可在固定高度容器內拖動的影像的頂部偏移量。所以我可以得到百分比而不是像素的值,并使用該值來設定容器“.container”中影像的 CSS 頂部位置,具體取決于容器的高度。
<div class="container">
<img src="" alt="" class="image">
</div>
<script src="http://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.1/jquery-ui.min.js"></script>
<style>
.container{
position: relative;
width: 960px;
height: 300px;
overflow: hidden;
}
.image{
top: 0;
width: 100%;
min-height: 100%;
min-width: 100%;
}
</style>
// JS
$(document).ready(function () {
let $container = $('.container');
let $image = $('.image');
let $conWidth = $($container).width();
let $conHeight = $($container).height();
let $imgWidth = $image.width();
let $imgHeight = $image.height();
$image.draggable({
disabled: false,
scroll: false,
axis: 'x, y',
cursor : 'move',
drag: (e, ui)=>{
if(ui.position.top >= 0) ui.position.top = 0;
if(ui.position.top <= $conHeight - $imgHeight)
ui.position.top = $conHeight - $imgHeight;
if(ui.position.left >= 0) ui.position.left = 0;
if(ui.position.left <= $conWidth - $imgWidth)
ui.position.left = $conWidth - $imgWidth;
},
stop: (e, ui)=>{
let $offsetHeight = ui.position.top;
let $offsetWidth = ui.position.left;
let realImageHeight = ($conWidth * $conHeight / $imgWidth) - $imgHeight;
let $top = ($realImageHeight * $offsetHeight / 100 * -1)/100;
console.log($top) // $top value in percent to be used as top positioning CSS
}
});
});
uj5u.com熱心網友回復:
考慮以下。
$(() => {
var $image = $('.image');
var $conHeight = $($container).height();
function percentFormat(dec) {
return Math.round(dec * 100) "%";
}
$image.draggable({
disabled: false,
scroll: false,
axis: 'x, y',
cursor: 'move',
start: (e, ui) => {
console.log(percentFormat($image.position().top / $conHeight));
},
drag: (e, ui) => {
console.log(percentFormat(ui.position.top / $conHeight));
},
stop: (e, ui) => {
console.log(percentFormat(ui.position.top / $conHeight));
}
});
});
.container {
position: relative;
width: 960px;
height: 300px;
overflow: hidden;
}
.image {
top: 0;
width: 100%;
min-height: 100%;
min-width: 100%;
}
<script src="http://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.1/jquery-ui.min.js"></script>
<div class="container">
<img src="" alt="" class="image">
</div>
如果您需要計算top百分比,演算法將是:position.top / container.height. 示例:120 / 300 = 0.4。我們知道有一個介于 0 和 1 之間的值。要使其成為介于 0 和 100 之間的百分比,我們可以將十進制值乘以 100 (120 / 300) * 100 = 40。。這個例子很干凈,但你可能會得到類似 的東西(85 / 300) * 100 = 28.3333333333,它不能得到很好的百分比。我用 Round 來清理它,得到最終值28%。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/480787.html
標籤:javascript jQuery jQuery-ui
下一篇:在Windows作業系統上使用Python在Chrome或Firefox中打開一個新的非焦點選項卡(或具有此選項的其他瀏覽器/方法)
