簡體   English   中英

停止div動畫超過容器邊緣

[英]stop div animating past container edge

我一直在使用JavaScript圖像全景鏡頭,從這里的代碼中砍掉它們並切碎在一起...現在我已經放棄了它,希望使用一種更簡單的方法,但是需要有關如何做幾件事的建議。

我有用於左右按鈕的代碼。

<div id="wrap">

<div class="entrance-hall pan-image">


</div>
</div>

<input type="button" value="Move Left" class="nav-left" onclick="pan_animate('-=20%')"  />
<input type="button" value="Move Right" class="nav-right"  onclick="pan_animate('+=20%')" />

這是針對javascript的。

function pan_animate(px) {
$('.pan-image').animate({
    'marginLeft' : px
});
}

它在包裝div內左右平移圖像20%,但是我想...

  1. 使它平滑滾動,而不是以百分比遞增
  2. 停止經過左右容器的邊緣
  3. 從圖像的中心開始。

要求不高嗎? 希望這有道理,並且有人可以提供幫助!

干杯。

添加的CSS

#wrap {
margin-bottom:60px;
border:4px solid white;
overflow:hidden;
}


 .pan-image {
position:relative;
width:2106px; 
height:395px;
left:50%;
margin-left:-1053px;
 }

 /* -- ===entrance hall=== -- */

.entrance-hall { 
background:url(/staging/kennawayhouse.org.uk/images/1-entrance-hall.jpg);
}
  • 使它平滑滾動,而不是以百分比遞增

實現此目的的一種方法是簡單地使用easing函數。 從jQuery動畫API:

緩和

.animate()的其余參數是命名要使用的緩動函數的字符串。 緩動函數指定動畫在動畫中不同點處進行的速度。 jQuery庫中唯一的緩動實現是默認的實現(稱為swing),以及以恆定速度進行擴展的實現(稱為linear)。 通過使用插件,可以使用更多輕松功能,其中最著名的是jQuery UI套件。

然后可以將您的代碼更改為:

function pan_animate(px) {
    $('.pan-image').animate({'marginLeft' : px}, 'linear'); // Swing and Linear comes in jQuery, but swing is the default value.
}

並且會感覺到一些平滑。

  • 停止越過左右容器的邊緣

這將需要一些css hack,但是position:absolute;left:5x;top:5px 可能會解決您有關內部元素的問題。 如果你想要一個答案比5月更准確,你可以發表你的CSS代碼。

編輯

根據您的CSS代碼,我實現了一個功能,該功能可以在移動時警告您的保證金是否已超過其父代的限制:

function pan_animate(px) {

    $marginLeftCss = $(".pan-image").css("marginLeft").replace(/[^-\d\.]/g, '');
    $n = px.replace(/[^-\d\.]/g, '');
    $x = (px.indexOf("-")==0) ? 1 - ($n/100):($n/100);

    $marginLeft = $marginLeftCss * $x;

    $width = $(".pan-image").width();
    $width += $(".pan-image").parent().width();

    if($marginLeft > - $width && $marginLeft < $width) //4212 = width*2
        $('.pan-image').animate({'marginLeft' : px}, 'linear');
    else
        alert("pan image reached it\'s end "  + $marginLeft);
}

您可以檢查它是一個小提琴: http : //jsfiddle.net/brunovieira/3wHn3/7/

  • 從圖像的中心開始。

為了使$(".pan-image")元素居中,可以使用兩種方法,css一種: position:relative;margin-left:auto;margin-right:auto ,或者如果position relative不是選項,您可以使用jQuery將元素居中, 例如

$parentHeight = $(".pan-image").parent().height();
$parentWidth = $(".pan-image").parent().width();

$panImageHeight = $(".pan-image").height();
$panImageWidth = $(".pan-image").width();

$(".pan-image").css('position','absolute','top',($parentHeight - $panImageHeight)/2 + 'px', 'left',($parentWidth - $panImageWidth)/2+'px');

同樣,根據您的編碼,上面回答的條件可能不起作用。

暫無
暫無

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

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