gpt4 book ai didi

javascript - 背景 CSS 剪辑路径问题

转载 作者:太空宇宙 更新时间:2023-11-04 05:53:12 25 4
gpt4 key购买 nike

我目前正在实现一个开关。问题是应该被开关隐藏的背景在左端显示一条细线。我完全不知道为什么。奇怪的是,SO 上的一切看起来都非常好。该开关位于一个可滚动的主包装器中,其中包含所有其他内容。我认为这可能是问题所在,但在删除滚动后,错误仍然存​​在:

enter image description here

当我运行检查器并将元素悬停时,背景似乎消失了:

enter image description here

这是我的代码。我已经尝试过低但找不到问题:

let toggle = document.getElementById('container');
let toggleContainer = jQuery('#toggle-container');
let toggleNumber;

jQuery('#container').click( function() {
toggleNumber = !toggleNumber;
if (toggleNumber) {
toggleContainer.css( "clip-path", "inset(0 0 0 50%)" );
} else {
toggleContainer.css( "clip-path", "inset(0 50% 0 0)" );
}
});
#container {
width: 100%;
height: 56px;
margin-bottom: 20px;
position: relative;
overflow: hidden;
user-select: none;
cursor: pointer;
border-radius: 3px;
-webkit-box-shadow: 0 0.2rem 0.4rem 0 rgba(0, 0, 0, .2);
box-shadow: 0 0.12rem 0.4rem 0 rgba(0, 0, 0, .2);
}

.inner-container {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
text-transform: uppercase;
}

.inner-container:first-child {
background: gray;
color: #ffffff;
}

.inner-container:nth-child(2) {
background: chartreuse;
color: #ffffff;
clip-path: inset(0 50% 0 0);
-webkit-transition: 0.2s;
-o-transition: 0.2s;
transition: 0.2s;
}

.toggle {
width: 50%;
position: absolute;
height: inherit;
display: flex;
font-weight: 600;
}

.toggle p {
margin: auto;
}

.toggle:nth-child(1) {
right: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<div class="inner-container">
<div class="toggle">
<p>Private</p>
</div>
<div class="toggle">
<p>Public</p>
</div>
</div>
<div class="inner-container" id='toggle-container'>
<div class="toggle">
<p>Private</p>
</div>
<div class="toggle">
<p>Public</p>
</div>
</div>
</div>

最佳答案

我建议使用更少代码且不使用 clip-path 的优化版本:

let toggle = document.getElementById('container');
let toggleContainer = jQuery('.inner-container');

jQuery('#container').click(function() {
toggleContainer.toggleClass('second');
});
#container {
margin-bottom: 20px;
user-select: none;
cursor: pointer;
border-radius: 3px;
box-shadow: 0 0.12rem 0.4rem 0 rgba(0, 0, 0, .2);
}

.inner-container {
height: 56px;
text-transform: uppercase;
display: flex;
background:
linear-gradient(chartreuse,chartreuse) left/50% 100% no-repeat,
gray;
color: #ffffff;
transition: 0.2s;
}
.inner-container.second {
background-position:right;
}

.toggle {
width: 50%;
display: flex;
font-weight: 600;
}

.toggle p {
margin: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<div class="inner-container">
<div class="toggle">
<p>Private</p>
</div>
<div class="toggle">
<p>Public</p>
</div>
</div>
</div>

关于javascript - 背景 CSS 剪辑路径问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58074922/

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