博主也是在學js,老師出了這麼一道題,博主用自己有限的知識,用tranform來實現了盒子的移動效果,這串代碼兼容不同大小的瀏覽器,兼容性挺好的。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
div{
width: 50px;
height: 50px;
background-color: yellow;
position: absolute;
left:10px;
top:50px;
}
</style>
</head>
<body>
<button id="btn">移動</button>
<div id="ff"></div>
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
var wid=0;
var hei=0;
var offset=$('#ff').offset();
var widd= 0;
var heii=0;
var ll=widd/heii;
$('#btn').mouseover(function () {//每當鼠標移動到按鈕上就自動獲取要移動的長度和寬度,兼容不同大小的瀏覽器
widd=$(document).width()-offset.left-document.getElementById('ff').clientWidth;//瀏覽器的總寬度要減去div這個元素離body元素的寬度,再減去他自身
heii=$(document).height()-offset.top-document.getElementById('ff').clientHeight;
ll=widd/heii;//算出寬相比於高要移動多少
})
$('#btn').click(function () {
setInterval(function () {//利用循環定時器來實現移動效果
hei++;
wid+=ll;
if (wid>widd&&hei>heii){//當數值超過要移動的長度和寬度時會停下來,精度+-1
return;
}
$("#ff").css("transform",`translate(${wid}px,${hei}px)`);},5);//時間定5毫秒刷新頻率很高
})
</script>
</body>
</html>
如果問題歡迎留言。