首页 > 解决方案 > 通过屏幕旋转更改图像宽度和高度

问题描述

请告诉我如何使用 javascript 通过方向更改来更改图像的宽度和高度。不幸的是,我的代码不起作用,这里是:

<script>window.addEventListener("orientationchange", function screenrotation() {
      var firstresposniverowphoto = document.getElementById("#firstresposniverowphoto");
      var secondresposniverowphoto = document.getElementById("#secondresposniverowphoto");
      if(screen.orientation=="portrait"){
          firstresposniverowphoto.width = '100%';
          secondresposniverowphoto.width = '100%';
      }if(screen.orientation=="landscape"){
          firstresposniverowphoto.width = '40vw';
          secondresposniverowphoto.width = '40vw';
      }                  
}, false);
</script>

标签: javascripthtmlcss

解决方案


谢谢大家的答案!我知道我做了一件非常愚蠢的事情,要求用 JavaScript 解决我之前描述的问题。相反,我意识到使用 CSS 比使用 JavaScript 更好。这是我的解决方案:

@media screen and (orientation: landscape) {

.contentOne{
box-shadow: 0 1vw 3vw 0 rgba(0,0,0,0.2);
transition: 0.3s;
background-repeat: no-repeat;
background-size: cover; 
height:40vh;
width:40vw;
}
.contentOne:hover{
box-shadow: 0 2vw 4vw 0 rgba(0,0,0,0.4);
}
}

@media screen and (orientation: portrait) {

.contentOne{
box-shadow: 0 1vw 3vw 0 rgba(0,0,0,0.2);
transition: 0.3s;
background-repeat: no-repeat;
background-size: cover; 
width:100%;
height:40vh;
margin:auto;
}
.contentOne:hover{
box-shadow: 0 2vw 4vw 0 rgba(0,0,0,0.4);
}
}

推荐阅读