Javascript 如何最大限度地减少媒体查询重复的类名?

Javascript 如何最大限度地减少媒体查询重复的类名?,javascript,html,css,Javascript,Html,Css,在这里,我编写了不同分辨率的媒体查询,但只更改了一个特定属性。我觉得这是重复的 @media (min-width: 325px) and (max-width: 420px) { .hero-banner{ height: 870px; background-position: center center !important; background-position-y: -120px !important; } } @me

在这里,我编写了不同分辨率的媒体查询,但只更改了一个特定属性。我觉得这是重复的

@media (min-width: 325px) and (max-width: 420px) { 
    .hero-banner{
        height: 870px;
        background-position: center center !important;
        background-position-y: -120px !important;
    }
}

@media (min-width: 421px) and (max-width: 480px) { 
    .hero-banner{
        height: 870px;
        background-position: center center !important;
        background-position-y: -180px !important;
    }
  }

@media (min-width: 481px) and (max-width: 540px) { 
    .hero-banner{
        height: 870px;
        background-position: center center !important;
        background-position-y: -220px !important;
    }
  }

@media (min-width: 541px) and (max-width: 600px) { 
    .hero-banner{
        height: 870px;
        background-position: center center !important;
        background-position-y: -280px !important;
    }
  }

@media (min-width: 601px) and (max-width: 660px) { 
    .hero-banner{
        height: 870px;
        background-position: center center !important;
        background-position-y: -340px !important;
    }
  }

@media (min-width: 661px) and (max-width: 720px) { 
    .hero-banner{
        height: 870px;
        background-position: center center !important;
        background-position-y: -400px !important;
    }
  }

@media (min-width: 721px) and (max-width: 767px) { 
    .hero-banner{
        height: 870px;
        background-position: center center !important;
        background-position-y: -460px !important;
    }
  }


在上述代码中,所有媒体查询中只有background-position-y在更改。有没有什么方法可以简化它,使代码看起来更干净。非常感谢您的帮助或建议。

尝试查看javascript
matchMedia

可以创建包含宽度和样式值的对象数组

const info = [
  {
    width: 720,
    style: -120
  },
  {
    width: 480,
    style: -180
  }
]
然后循环设置css值

info.forEach(obj => {
   let i = window.matchMedia(`(min-width: ${obj.width}px)`)
   if(i.matches){
      document.getElementById("hero").style.backgroundPositionY = obj.style
   }
})
有关这方面的更多信息:

尝试查看javascript
matchMedia

可以创建包含宽度和样式值的对象数组

const info = [
  {
    width: 720,
    style: -120
  },
  {
    width: 480,
    style: -180
  }
]
然后循环设置css值

info.forEach(obj => {
   let i = window.matchMedia(`(min-width: ${obj.width}px)`)
   if(i.matches){
      document.getElementById("hero").style.backgroundPositionY = obj.style
   }
})
有关这方面的更多信息:

嘿,L,这应该是一个评论。但是因为你不能用较少的代表性来评论,我建议用一个例子来扩展你的答案。是的,我想评论,无论如何我会扩展它谢谢:)嘿,我,这应该是一个评论。但是,由于您不能用较少的代表性进行评论,我建议您用一个例子来扩展您的答案。是的,我想评论,无论如何,我会扩展它。谢谢:)在媒体查询中,您只需要拥有每个
background-position-y
的特定内容,因为其余内容都是相同的。在媒体查询中,您只需要拥有每个
background-position-y
的特定内容,因为其余内容都是相同的。