2014-05-07 127 views
0

我正在寫一些代碼,使div滑動到頁面的左側或右側,具體取決於某些按鍵(左或右箭頭)。這是我的腳本。jquery滑動div只能工作一次

$(document).keydown(function(e){ 
    var $inner = $('.inner-cover'); 
    if (e.keyCode == 39) { 
    $inner.css({ 
     position: 'fixed', 
     top: $inner.offset().top, 
     left: $inner.offset().left 
    }).animate({left:'100%'}, 1000); 
    } 
    if (e.keyCode == 37){ 
    $inner.css({ 
     position: 'fixed', 
     top: $inner.offset().top, 
     right: $inner.offset().right 
    }).animate({right:'100%'}, 1000); 
    } 
}); 

這裏是它在jsfiddle中的鏈接。 http://jsfiddle.net/e32A3/

我有幾個關於它的問題,我真的很想回答,因爲我似乎沒有正確理解這一點。

爲什麼滑動功能只能使用一次或兩次?

爲什麼我需要把

$inner.css({}).animate({left:'100%'},1000); 

我試圖

$inner.animate({left:100%},1000); 

,並沒有奏效

此外,我怎麼會阻止它的中心?我想我必須做的事情沿線

animate({left:($(window).width()-$inner.width())/2)},1000); 

但我再次嘗試過,它沒有工作。

+0

,因爲'position'應該設置爲'fixed'或'absolute'或'relative'以使'left'生效。 –

+0

也注意到'offset()'返回一個沒有'right'或'bottom'屬性的對象,它只有'left'和'top'。 –

回答

2

試試這個:

if (e.keyCode == 37){ 
$inner.css({ 
    position: 'fixed', 
    top: $inner.offset().top 
}).animate({left:'-100%'}, 1000);} 

Working Demo

1

試試這個:

$(document).keydown(function (e) { 
var $inner = $('.inner-cover'); 
if (e.keyCode == 39) { 
    $inner.css({ 
     position: 'fixed', 
     top: $inner.offset().top, 
     left: $inner.offset().left 
    }).animate({ 
     left: '100%', 
     right: 'auto' 
    }, 1000); 
} 
if (e.keyCode == 37) { 
    $inner.css({ 
     position: 'fixed', 
     top: $inner.offset().top, 
    }).animate({ 
     right: '100%', 
     left: 'auto' 
    }, 1000); 
} 
}); 

新增right"auto"而不是offset().right,沒有什麼作爲offset().right。偏移僅包含頂部和左側值。 演示:http://jsfiddle.net/lotusgodkk/e32A3/2/

0

爲什麼滑動功能只能工作一次或兩次?

因爲在第二次運行它已經財產「左:100%」

爲什麼我需要把

因爲設置「左」或「右」將才生效元素的位置設置爲固定/絕對/相對

另外,我會如何阻止它在中心?

在中心設置設置

$inner.animate({left:window.(innerWidth-$inner.width)/2+"px"}) 

最後,你需要的ATTR「左」或「右」一個操作和設置在CSS元素的位置

JS:

$(document).keydown(function(e){ 
var $inner = $('.inner-cover'); 
if (e.keyCode == 39) { 
    $inner.animate({left:($(window).width() - $inner.width())+"px"}, 1000); 
    //this to set on middle//$inner.animate({left:($(window).width() - $inner.width())/2+"px"}, 1000); 
} 
if (e.keyCode == 37){ 
$inner.animate({left:0}, 1000); 
} 
}); 

CSS:

.inner-cover { 
position:fixed; 
width:200px; 
left:50%; 
top:50%; 
background-color:green; 
}