我可以将这些功能组合到一个简化的功能中吗?
我正在单击几个不同的实例,在单击时交换背景图像,并且仅针对991px及以上的屏幕。我可以创建一个简化的功能还是使它更简洁/更好?
const mediaQuery = window.matchMedia('(min-width: 991px)')
const infraTab1 = document.querySelector(".content1")
const infraTab2 = document.querySelector(".content2")
const infraTab3 = document.querySelector(".content3")
const infraTab4 = document.querySelector(".content4")
const infrastructure = document.querySelector(".infrastructure")
if (mediaQuery.matches) {
infraTab1.addEventListener("click", function () {
infrastructure.style.backgroundImage = "url(img1.jpg)";
})
}
if (mediaQuery.matches) {
infraTab2.addEventListener("click", function () {
infrastructure.style.backgroundImage = "url(img2.jpg)";
})
}
if (mediaQuery.matches) {
infraTab3.addEventListener("click", function () {
infrastructure.style.backgroundImage = "url(img3.jpg)";
})
}
if (mediaQuery.matches) {
infraTab4.addEventListener("click", function () {
infrastructure.style.backgroundImage = "url(img4.jpg)";
})
}
I am swapping out background images on click for several different instances, and also only targeting screens at 991px and above. Can I create one, streamlined function or make this more concise/better?
const mediaQuery = window.matchMedia('(min-width: 991px)')
const infraTab1 = document.querySelector(".content1")
const infraTab2 = document.querySelector(".content2")
const infraTab3 = document.querySelector(".content3")
const infraTab4 = document.querySelector(".content4")
const infrastructure = document.querySelector(".infrastructure")
if (mediaQuery.matches) {
infraTab1.addEventListener("click", function () {
infrastructure.style.backgroundImage = "url(img1.jpg)";
})
}
if (mediaQuery.matches) {
infraTab2.addEventListener("click", function () {
infrastructure.style.backgroundImage = "url(img2.jpg)";
})
}
if (mediaQuery.matches) {
infraTab3.addEventListener("click", function () {
infrastructure.style.backgroundImage = "url(img3.jpg)";
})
}
if (mediaQuery.matches) {
infraTab4.addEventListener("click", function () {
infrastructure.style.backgroundImage = "url(img4.jpg)";
})
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
也许这是您想要的解决方案
Maybe, This is the solution which you want