簡體   English   中英

JavaScript隱藏/顯示動畫

[英]JavaScript Hide/Show Animation

我想單擊我的圖像,使其消失並在其他位置移至右側。 目前,我的圖片在右側屏幕上顯示。 請幫助我使用允許我的圖像隱藏和顯示的timeout()創建代碼。

php code
<div id= "ben" style= "position: relative; visibility: visible;" onclick="moveRight()" >
<img src = "images/ben.JPG" height = "250" width = "200" alt= "Picture of Peek-a-boo Ben"/>


//JavaScript for a hide/show image in different location
var ben = null;
var animate ;
function init(){
   ben = document.getElementById('ben');
   ben.style.position= 'relative'; 
   ben.style.left = '0px'; 
}
function moveRight(){
   ben.style.left = parseInt(ben.style.left) + 10 + 'px';
   animate = setTimeout(moveRight,20); // call moveRight in 20msec
}
function stop(){
   clearTimeout(animate);
   ben.style.left = '0px'; 
}
window.onload =init;

我絕對會為此使用jquery...。

但是,如果您希望使用純JavaScript,就在這里。盡管動畫是使用CSS完成的。

//JavaScript for a hide/show image in different location
var ben = null;
var animate=0 ;
function init(){
  ben = document.getElementById('ben');
 }

 function toggled(){

  var image = document.getElementById('image2');
  if( animate==0){
   animate = 1;
  image.className= "right";} 
  else if(animate==1){
   animate=0;
  image.className= "left";}
 }

 window.onload =init;

DEMO HERE ....只需在CSS中調整From和To即可將其移至更近

以及相關的CSS ...

.right {
-webkit-transform: translateX(150px);
-webkit-animation-name: right;
-webkit-animation-duration: 2s;
-webkit-animation-iteration-count: 1;
}

.left {
 -webkit-transform: translateX(0px);
-webkit-animation-name: left;
-webkit-animation-duration: 2s;
-webkit-animation-iteration-count: 1;
}
 @-webkit-keyframes right { from { -webkit-transform: translateX(0px); }
 to {  -webkit-transform: translateX(150px);  }}

 @-webkit-keyframes left { from { -webkit-transform: translateX(150px); }
 to {  -webkit-transform: translateX(0px);  }}

編輯

這是使用JQuery編寫的...不需要CSS .....上面^^上的所有這些代碼行都減少為兩個..... gotta喜歡Jquery :)實際上,使用內置的toggle() )功能...

var tog=0;
$('#ben').click(function(){
if(tog==0){$('#image2').animate({marginLeft: "250"}, 1500);tog=1; return false;}
else if(tog==1){$('#image2').animate({marginLeft: "0"}, 1500);tog=0; return false;
} });

此處演示

(注意...如果您打算使用此代碼,則必須包括Jquery庫,並調用$(document).ready(function(){...

另外,您不必再在HTML中進行onclick了...

ie... <div onclick="moveRight()">

當Jquery為您處理時,請使用click()

暫無
暫無

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

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