2015-11-10 97 views
0

我试图写一点Javascript将会拍摄一个图像(目前,它只是一个测试图像500x400说“这是一个测试”),并减少宽度每隔一段时间,给人一种旋转的印象;然后,当宽度达到零时,宽度再次增加,使其看起来像它再次开放。setInterval增量增加/减少图像宽度

我已经写了一些不整洁的代码,需要大概;此刻,我只是想尝试一些工作,但我无法工作,任何人都可以帮忙?

<html> 
<body> 

<center> 
<img src="sign.jpg" id="sign" width="500"> 
</center> 

<script> 
var decreasing=true; 
var currentWidth=500; 
var deltaWidth=5; 
var myVar = setInterval(function(){ changeWidth() }, 500); 

function changeWidth() 
{ 

if(decreasing == true) 
{ 
currentWidth=-deltaWidth; 
document.getElementById("sign").width = currentWidth; 

if(currentWidth<=0) 
{ 
    decreasing = false; 
} 
} 
else 
{ 
currentWidth=+deltaWidth; 
document.getElementById("sign").width = currentWidth; 

if(currentWidth>=500) 
{ 
    decreasing = true; 
} 
} 


} 

</script> 

</body> 
</html> 
+0

你期待这个http://jsfiddle.net/kishoresahas/j0m50uop/1/? –

+0

@KishoreSahas我不认为你理解这个问题 – Jamiec

回答

1

您的操作方法错误。 =-=+应该是-=+=

function changeWidth() 
{ 

    if(decreasing == true) 
    { 
     currentWidth -= deltaWidth; 

     // ... 
    } 

} 
-1

尝试使用setAttribute-Function更改属性。你可以用CSS3 Animate做这样的事情。

-1

务必:

document.getElementById("sign").style.width = currentWidth + "px" 

然后用适当的CSS所以图像进行调整,如添加

max-width: 100% 

的图像元素。

0

我可以在代码中看到两个问题。

  1. 您的赋值操作符是错误的方法。要增加一个值,你可以使用i = i + 1这个形式的代码,我缩短到i += 1
  2. 除非您设置高度,否则当您更改图像的width时,浏览器可能希望按比例调整height的大小。下面

代码工作:

var decreasing=true; 
 
var currentWidth=500; 
 
var deltaWidth=5; 
 
var myVar = setInterval(function(){ changeWidth() }, 100); 
 

 
function changeWidth() 
 
{ 
 

 
    document.getElementById("sign").height = 400; 
 
    if(decreasing == true) 
 
    { 
 
     currentWidth-=deltaWidth; 
 
     document.getElementById("sign").width = currentWidth; 
 
     if(currentWidth<=0) 
 
     { 
 
      decreasing = false; 
 
     } 
 
    } 
 
    else 
 
    { 
 
     currentWidth+=deltaWidth; 
 
     document.getElementById("sign").width = currentWidth; 
 

 
     if(currentWidth>=500) 
 
     { 
 
      decreasing = true; 
 
     } 
 
    } 
 
}
<img id="sign" src="http://placehold.it/500x400" />

0

你的运营商都走错了路。将=-更改为-==++=。另外,请考虑在图像上设置高度并加快间隔。这是一个工作解决方案fiddle