我试图将指针的底部定位在速度计中心底部的一个位置,而不是移动它。
请注意,除了 transform: rotate(40deg)
的度数,我不能更改 HTML 来表示 transform: rotate(-80deg)
但不能更多。但是我可以编辑 CSS。
.speedometer {
display: inline-block;
width: 200px;
height: 109px;
overflow:hidden;
margin: 0 auto;
text-align: center;
background-repeat: no-repeat;
background-size: contain;
}
.needle {
width: 25px;
height: 70px;
left: 90px;
position: absolute;
top: 40px;
transform-origin: bottom;
background-size: contain;
background-repeat: no-repeat;
}
<div>
<div class="speedometer" style="background-image: url('https://i.ibb.co/LQCv5CR/taxometer.png')"></div>
<div class="needle" style="background-image: url('https://i.ibb.co/JrthWtD/needle.png'); transform: rotate(40deg);"></div>
<div class="needle" style="background-image: url('https://i.ibb.co/JrthWtD/needle.png'); transform: rotate(-80deg);"></div>
</div>
首先使主要元素具有速度计背景,因此指针是子元素。然后将它们相对于底部的速度表放置并水平居中。最后调整变换原点,使其恰好位于针圆的中心。
.speedometer {
width: 200px;
height: 109px;
margin: 0 auto;
background: url('https://i.ibb.co/LQCv5CR/taxometer.png') center/contain no-repeat;
position: relative;
}
.needle {
position: absolute;
left: calc(50% - 12px);
bottom: -6px;
width: 24px;
height:78px;
transform-origin: 50% calc(100% - 12px);
background: url('https://i.ibb.co/JrthWtD/needle.png') center/contain no-repeat;
}
<div class="speedometer" >
<div class="needle" style=" transform: rotate(40deg);"></div>
<div class="needle" style=" transform: rotate(10deg);"></div>
<div class="needle" style=" transform: rotate(-60deg);"></div>
<div class="needle" style=" transform: rotate(80deg);"></div>
<div class="needle" style=" transform: rotate(-90deg);"></div>
</div>
因为它是关于一根针的,你可以像下面这样优化:
.speedometer {
width: 200px;
height: 109px;
display:inline-block;
background: url('https://i.ibb.co/LQCv5CR/taxometer.png') center/contain no-repeat;
position: relative;
}
.speedometer::before {
content:"";
position: absolute;
left: calc(50% - 12px);
bottom: -6px;
width: 24px;
height:78px;
transform-origin: 50% calc(100% - 12px);
background: url('https://i.ibb.co/JrthWtD/needle.png') center/contain no-repeat;
transform:rotate(var(--r,0deg));
transition:0.8s;
}
.speedometer:hover::before {
transform:rotate(0deg);
}
<div class="speedometer" style="--r:60deg">
</div>
<div class="speedometer" style="--r:-50deg">
</div>
<div class="speedometer" style="--r:-80deg">
</div>
我是一名优秀的程序员,十分优秀!