我想点击我的图片,让它消失,然后在另一个位置向右移动。目前,我的图像在屏幕右侧运行。请帮助我使用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;
答案 0 :(得分:1)
我绝对会亲自使用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必需.....所有那些代码行^^减少到两个.....得爱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()