在项目中,需要在各个页面的某些地方,配置展示不同地址的二维码。而这些二维码的样式都是通过:before及:after的css实现,样式全局只使用一个类名。如何
只用css(不使用js)动态高效来展示不同地址的二维码图片,本文列举相关处理方案
1、示例基础
<style>
.slots-qr-code {
position: relative;
}
.slots-qr-code:hover::before {
position: absolute;
left: 50%;
transform: translateX(-50%);
z-index: 11;
content: "";
width: 233px;
height: 233px;
background: #FFFFFF;
background-image: url(./qr1.jpg);
background-repeat: no-repeat;
background-size: 120px 120px;
background-position-x: center;
background-position-y: 37px;
box-shadow: -4px 0px 8px 0px rgba(0, 0, 0, 0.1);
border-radius: 24px;
font-weight: normal;
}
.slots-qr-code:hover::after {
content: "Scan the QR code download to phone";
position: absolute;
left: 50%;
transform: translateX(-50%);
z-index: 13;
top: 162px;
width: 174px;
height: 50px;
font-size: 18px;
text-align: center;
color: #000;
font-weight: normal;
}
.slots-qr-code:active::before,
.slots-qr-code:active::after {
display: none;
}
</style>
<div style="height: 100px;width: 100px;margin: auto;border: 1px solid #000;" class="slots-qr-code">鼠标移入展示</div>
2、常规处理方式:
- 通过class名称和js,来动态切换
<style>
.slots-qr-code2:hover::before {
background-image: url(./qr2.jpg);
}
</style>
<div style="height: 100px;width: 100px;margin: auto;border: 1px solid #000;" class="slots-qr-code">鼠标移入展示</div>
<script>
document.querySelector(".slots-qr-code").classList.add("slots-qr-code2")
</script>
- 单纯用js更改
<div style="height: 100px;width: 100px;margin: auto;border: 1px solid #000;" class="slots-qr-code">鼠标移入展示</div>
<script>
var style = document.createElement("style");
style.appendChild(document.createTextNode(".slots-qr-code:hover::before {background-image: url(./qr2.jpg);}"))
document.body.appendChild(style);
</script>
3、使用css变量处理:
<style>
.slots-qr-code:hover::before {
background-image: var(--slots-qr-code-url);
/* 把基础样式里面的 background-image 更换下*/
}
</style>
<div style="--slots-qr-code-url:url('./qr1.jpg');height: 100px;width: 100px;margin: auto;border: 1px solid #000;"
class="slots-qr-code">鼠标移入展示</div>
<div style="--slots-qr-code-url:url('./qr2.jpg');height: 100px;width: 100px;margin: auto;border: 1px solid #000;" class="slots-qr-code">鼠标移入展示</div>
- 注意:
url()必须放在style才可以实现具体效果 - 优势:
- 1、简洁和可维护性,减少样式冗余
- 2、CSS变量可以在运行时动态地修改,具有动态性
- 3、样式模块化和可重用,具有作用域控制
- 4、响应式设计