使用Sass基于视口动态显示静态图像

问题描述 投票:0回答:1

我正在创建一个在登录页面上显示hero的React应用程序,该应用程序显示三个图像之一:[hero-1.jpg, hero-2.png, hero-3.png]基于用户的viewport screen大小。

我尝试在网上查找展示实现此目的的DRY方法的资源一直没有成功,为了参与,我将尝试的这段代码留给我-从理论上讲对我来说是有意义的。

N.B。我对Sass / Scss非常陌生

snippet.html

<section className="hero is-fullheight has-background-black">
      <div className="hero-body">
           <div className="container">
           </div>
      </div>
</section>

hero.scss

$i: 1;
$breakpoint-phone: 480px;
$breakpoint-tablet: 768px;
$breakpoint-desktop: 1024px;

@mixin modifier ($i:1) {
    @content;    
    @media only screen and (max-width:$breakpoint-phone) { $i: 2; }
    @media only screen and (max-width:$breakpoint-tablet) { $i: 3; }
    @media only screen and (max-width:$breakpoint-desktop) { $i: 1; }
}

.hero {
    background-position: center;
    background-size: cover
}

@include modifier {.hero {background-image: url('../assets/hero-#{$i}.jpg');}}

方法

  1. 默认显示内容(从@include中提取)。
  2. [Mixin modifier将修改传递给mixin的$i,该mixin插入在图像路径中。

预期结果:根据每个断点,将$i设置为适当的值并动态更改背景图像。

实际结果:使用全局$i,并且网页显示hero-1.jpg

image sass responsive viewport
1个回答
0
投票

有几种方法可以实现这一目标。如果我要这样做,这就是我要这样做的方式。

此外,实践移动优先开发也是非常明智的。使用min-width并向上移动,而不是使用max-width向下移动。当前的结构方式意味着如果文档顶部的$i变量未设置为1,则您将没有有效的URL。一旦习惯了,用这种方法编写SASS或CSS会容易得多。

$tablet: 768px;
$desktop: 1024px;

@mixin hero-image() {
  .hero {
  background-position: center;
  background-size: cover;
  background-image: url('../assets/hero-2.jpg');
  
  @media screen and (min-width: $tablet) {
     background-image: url('../assets/hero-3.jpg');
    }
    
   @media screen and (min-width: $desktop) {
    background-image: url('../assets/hero-1.jpg');
   }
  }
}

@include hero-image();

您仍然需要写3次background-image属性。这样做的方式很接近,但是您必须在消耗的scss文件中将@include modifier()重复3次。最终,SASS编译为CSS。您可能可以使用SASS函数或For Loop实现此目的,但是mixins可能变得非常复杂和强大,但难以阅读和理解。这就是我刚才向您展示的mixin在CSS中编译的结果。

.hero {
  background-position: center;
  background-size: cover;
  background-image: url("../assets/hero-2.jpg");
}
@media screen and (min-width: 768px) {
  .hero {
    background-image: url("../assets/hero-3.jpg");
  }
}
@media screen and (min-width: 1024px) {
  .hero {
    background-image: url("../assets/hero-1.jpg");
  }
}

我建议在编译实际项目之前将SCSS / SASS放入此编译器以查看结果。

https://www.sassmeister.com/

即使您在mixin中重复3次背景图像,这仍然是DRY代码,因为您可以在将要显示图像的任何地方都包含一个mixin,并且如果您需要对其进行编辑,则可以在其中进行编辑地点。

© www.soinside.com 2019 - 2024. All rights reserved.