透明度一直閃?
<!DOCTYPE?html>
<html?lang="en">
<head>
????<meta?charset="UTF-8">
????<meta?name="viewport"?content="width=device-width,?initial-scale=1.0">
????<title>Document</title>
????<style>
????????#box1{
????????????width:?400px;
????????????height:?400px;
????????????background-color:?blueviolet;
????????????opacity:?0.3;
????????}
????</style>
????<script>
????????window.onload?=?function(){
????????????var?box1?=?document.getElementById("box1");
????????????box1.onmouseover?=function(){
????????????????move(1);
????????????};
????????????box1.onmouseout?=function(){
????????????????move(0.3);
????????????}
????????}
????????var?timer?=?null;
????????var?opacity=0.3;
????????function?move(itarget){
????????????clearInterval(timer);
????????????var?box1?=?document.getElementById("box1");
????????????timer=setInterval(function(){
????????????????var?speed;
????????????????if(opacity>itarget){
????????????????????speed=-0.1
????????????????}
????????????????else{
????????????????????speed=0.1;
????????????????};
????????????????if(opacity==itarget){
????????????????????clearInterval(timer);
????????????????}
????????????????else{
????????????????????opacity+=speed;
????????????????????box1.style.opacity?=?opacity;
????????????????}
????????????},100)
????????}
????</script>
</head>
<body>
????<div?id="box1"></div>
</body>
</html>
透明度一直在1-1.1閃
往下的時候一直在0.3-0.2一直閃
求解
2;
2020-06-09
先說原因:由于小數(shù)在計算時會先轉(zhuǎn)換為二進制,存在精度丟失。
JS的小數(shù)運算常用的方法有兩種:
1. 先轉(zhuǎn)成整數(shù),例如代碼里的乘以100的做法
num.toFixed()方法,指定保留的小數(shù)位數(shù),在截取時會進行四舍五入。
實際上,無論移入移出鼠標,都在抖動的。
下面是控制臺輸出的透明度。
1.移入鼠標的透明度
2.移出鼠標的透明度
2020-05-05