简体   繁体   English

响应式设计由于某些原因不起作用

[英]Responsive design not working for some reasons

I am trying to show a different image on my website when its seen on computers and on phones, but for some reasons it just doesn't work当我在电脑和手机上看到它时,我试图在我的网站上显示不同的图像,但由于某些原因它不起作用

<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="utf-8">
  <link rel="icon" href="favicon.ico" />
  <style>
    .image {
    display: block;
    margin-left: auto;
    margin-right: auto;
    width: 95%;
    }
        
    body {
      background-color: rgb(30, 30, 30);
    }
  </style>
  <script>
    if (screen.width < screen.height) {
        document.getElementById("change").src = "phone.png";
    }
  </script>
</head>
<body>
  
  <div class="image">
    <img id="change" src="computer.png" class="image">
  </div>

</body>
</html>

I am quite sure that what I did wrong is extremely stupid, but I just can't find it, if you can help me, I'd be very grateful我很确定我做错的事情非常愚蠢,但我就是找不到,如果您能帮助我,我将不胜感激

You can do it with css as well.你也可以用css来做。

  .d-large {
    display: block;
  }
  .d-small{
    display:none;
  }

@media only screen and (max-width: 600px) {
  .d-large {
    display: none;
  }
  .d-small{
    display:block;
  }
}

<div class="small">
  <img id="img1" src="computer.png" class="image d-large">
  <img id="img2" src="phone.png" class="image d-small">
</div>

Yes, Martin has right, this is not the best of with js.是的,Martin 说得对,这不是最好的 js。

window.addEventListener('resize', function(event) {
    if (window.innerWidth < window.innerHeight) {
        document.getElementById("change").src = "computer.png";
    }else {
      document.getElementById("change").src = "phone.png";
    }
}, true);

tbh i dont see the problem either. tbh 我也没有看到问题。 I think, Instead of using that if statement, just use @mediaquery and image as background image?我认为,不要使用 if 语句,而是使用 @mediaquery 和 image 作为背景图像?

.image{
    @media screen and (max-width: 700px) {   
        background-image: url(http://subtlepatterns.com/patterns/dark_embroidery.png);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM