<style>
#img1{
opacity: 0.3;
}
</style>
<script type="text/javascript">
window.onload=function()
{
var oimg=document.getElementById('img1');
oimg.onmousemove=function()
{
movestar(1);
}
oimg.onmouseout=function()
{
movestar(0.3);
}
}
var timer=null;
var opa=0.3;
var speed=0;
function movestar(itarget)
{
var oimg=document.getElementById('img1');
clearInterval(timer);
timer=setInterval(function()
{
if(opa<itarget)
{
speed=0.1;
}
else
{
speed=-0.1;
}
if(opa==itarget)
{
clearInterval(timer);
}
else{
opa+=speed;
oimg.style.opacity=opa;
}
},30);
}
</script>
</head>
<body>
<img id="img1" src="img/IMG_5894.JPG" />
</body>
这是因为js的数字运算精度缺失问题,比如:0.7 + 0.1不是等于0.8而是0.7999999999999999,0.4 - 0.1不是0.3而是0.30000000000000004,不相信的话可以去浏览器试试。
所以你的代码需要改一个地方就可以了,把opa += speed
改成
opa = parseFloat((opa+speed).toFixed(10))
另外,你最好不要使用mousemove
,改成mouseover
或者mouseenter