[英]How can I move elements into view when the window is resized?
我有一個項目,我需要做一個水族館,里面的魚在點擊時聚集。
我已經做了一切,但問題是,程序應該可以調整大小。
我想說什么。 如果我調整瀏覽器窗口的大小,魚應該重新出現在窗口的可見位置並繼續游泳。
這是我的代碼:
<!DOCTYPE html>
<html>
<head>
<style>
body{background-color:aqua; width:100%; height:100%;padding:0; margin:0;}
img{width:50px; height:50px;}
div{position:absolute;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
i = 0;
function swim(fishid){
newLeft = Math.random()*1200; // due to new width
newTop = Math.random()*600; //due to new height
do_move(fishid, newTop, newLeft, Math.random()*1000);
}
function do_move(fishid, topPos, leftPos, timeToMove=0){
$("#"+fishid).css({"transform": "rotateY(0deg)"});
ll = leftPos + 'px';
tt = topPos + 'px';
if( parseInt($("#"+fishid).css('left'))>leftPos){
$("#"+fishid).css({"transform": "rotateY(180deg)"});
}
$("#"+fishid).animate({"left": ll, "top": tt}, 1000+timeToMove, function(){swim(fishid);});
}
$(document).ready(function(){
let fishes = Math.random()*5+5;
for(i=0; i<fishes; i++){
$("body").append('<div id="fish'+ i + '"><img src="http://icons.iconarchive.com/icons/icons8/ios7/256/Animals-Fish-icon.png"></div>');
swim("fish" + i);
}
$("*").click(function(ev){
$("div").each(function(){
$(this).stop();
do_move($(this).attr("id"), ev.pageY-25, ev.pageX);
});
});
$ ( window ).resize(function(){});// I have to do it with this also
});
</script>
</head>
<body>
</body>
</html>
使用實際窗口尺寸而不是硬編碼值:
newLeft = Math.random() * window.innerWidth * 0.9;
newTop = Math.random() * window.innerHeight * 0.9;
由於會重復調用swim()
函數,因此不需要調整大小事件處理程序。 這意味着有一小段時間魚可以逃出窗口,但在一個程序周期后解決。 將overflow: hidden
在主體上可在調整大小期間消除滾動條。
我已經引入了一個 90% 的任意減速器來考慮魚的大小。 那是可以調整的。
每當您調整屏幕大小時,都會觸發調整大小事件。 您可以類似地輕松獲取屏幕內部寬度和高度。
$(window).resize(function(e){
console.log($(this).innerWidth())
console.log($(this).innerHeight())
});
newLeft = Math.random() *$( window ).width();
newTop = Math.random() *$( window ).height()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.