在javascript中使图像移动适应窗口大小

时间:2018-12-28 16:58:57

标签: javascript html css image position

我在自己的网站上制作了一个动画,如果单击该动画,动画就会移动。问题是在管理它的javascript函数上,我给出了一系列坐标,这些坐标仅在浏览器为全屏模式时才适合。以下是一些示例:  https://imgur.com/a/Ug6eQlphttps://imgur.com/a/bPrVg5y 这是我的javascript函数:

function init(){
   imgObj = document.getElementById('minion');
   immagine = document.getElementById('immagine_minion');
   imgObj.style.position= 'absolute'; 
   imgObj.style.top = '240px';
   imgObj.style.left = '-300px';
   imgObj.style.visibility='hidden';
   appaer();
 }


例如,这是打开页面后立即移动它的方法:

function appaer(){
  immagine.src="../img/minion_dx.png";
  if (parseInt(imgObj.style.left)<200) {
   imgObj.style.left = parseInt(imgObj.style.left) + 5 + 'px';
   imgObj.style.visibility='visible';
   animate = setTimeout(appaer,20);
 } else 
 stop();
}

如何使其适合每种屏幕分辨率?

1 个答案:

答案 0 :(得分:0)

这应该可以帮助您入门

var stage_number = 0

function go_to_next_stage() {
  stage_number++
  var stage = document.getElementById("stage" + stage_number)
  me.style.left = getComputedStyle(stage).getPropertyValue("left")
  me.style.top = getComputedStyle(stage).getPropertyValue("top")
  if (stage_number > 3) stage_number = 0
}
img {
  position: absolute;
  left: -100px;
  top: 0;
  transition: left 2s, top 2s
}

.stage {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  position: absolute;
}

#stage1 {
  left: 0;
  top: 0;
}

#stage2 {
  right: 0;
  top: 0;
}

#stage3 {
  right: 0;
  bottom: 0;
}

#stage4 {
  left: 0;
  bottom: 0;
}

div {
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}
<img id="me" src="https://de.gravatar.com/userimage/95932142/195b7f5651ad2d4662c3c0e0dccd003b.png?size=100" />
<div onclick="go_to_next_stage()">click anywhere to continue</div>

<div class="stage" id="stage1">
</div>
<div class="stage" id="stage2">
</div>
<div class="stage" id="stage3">
</div>
<div class="stage" id="stage4">
</div>