gpt4 book ai didi

javascript - 如何使用 CSS 转换将加号变为减号?

转载 作者:搜寻专家 更新时间:2023-10-31 21:53:37 24 4
gpt4 key购买 nike

我想创建一个切换按钮,将其形状从加号变为减号。

仅使用 CSS使用伪元素

想要的效果是让“+”号中的竖线收缩成横线。

我知道这是可能的,但我不确定哪条路是最好的。我正在考虑对 height 做些什么,但我担心浏览器的 line-height 会改变它在元素中的位置。

$('button').on("click", function(){
$(this).toggleClass('active');
});
button {
color: #ecf0f1;
background: #e74c3c;
width: 50px;
height: 50px;
border: 0;
font-size: 1.5em;
}
button span {
transition: all .75s ease-in-out;
}
button.active span {
/* Code to morph + to - */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button><span>+</span></button>

最佳答案

由于形状简单,最简单的方法就是用元素制作+-。使用伪元素将是最干净的解决方案,但您也可以只使用 DOM 元素并拥有稍微困惑的文档结构。

考虑到这一点,实际的解决方案就很简单了。我们使用 CSS 来定位元素以类似于所需的字符,然后通过为该位置设置动画来在它们之间“变形”。

查看以下代码,并尝试理解每条规则的作用。

button {
color: #ecf0f1;
background: #e74c3c;
width: 50px;
height: 50px;
border: 0;
font-size: 1.5em;
position: relative;
}

button span {
position: absolute;
transition: 300ms;
background: white;
border-radius: 2px;
}

/* Create the "+" shape by positioning the spans absolutely */
button span:first-child {
top: 25%;
bottom: 25%;
width: 10%;
left: 45%;
}

button span:last-child {
left: 25%;
right: 25%;
height: 10%;
top: 45%;
}

/* Morph the shape when the button is hovered over */
button:hover span {
transform: rotate(90deg);
}

button:hover span:last-child {
left: 50%;
right: 50%;
}
<button>
<span></span>
<span></span>
</button>

关于javascript - 如何使用 CSS 转换将加号变为减号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38136077/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com