简体   繁体   English

如何使我的 CSS 切换 state 变化更平滑,例如通过过渡?

[英]How can I make my CSS toggle state changing smoother e.g. with a transition?

I've created a toggle in CSS:我在 CSS 中创建了一个切换:

 jQuery( document ).ready( function ( $ ) { $( document ).on( 'click', '.checkbox-toggle-wrapper.checkbox-toggle', function () { $( this ).toggleClass( 'enabled' ); } ) } );
 .checkbox-toggle-wrapper { margin-right: 12px; margin-top: 5px; margin-left: 1px; }.checkbox-toggle-wrapper.checkbox-toggle:not(.enabled)::before { right: auto; left: 0; }.checkbox-toggle-wrapper.checkbox-toggle:not(.enabled) { border-color: #999; background-color: #999; }.checkbox-toggle-wrapper.checkbox-toggle { height: 16px; width: 32px; border: 2px solid #00695c; background-color: #00695c; display: inline-block; text-indent: -9999px; border-radius: 10em; position: relative; margin-top: -1px; vertical-align: text-top; cursor: pointer; }.checkbox-toggle-wrapper.checkbox-toggle::before { content: ""; display: block; width: 16px; height: 16px; background: #fff; position: absolute; top: 0; right: 0; border-radius: 100%; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="checkbox-toggle-wrapper"> <span class="checkbox-toggle enabled"></span> </div>

I'm looking now for a way to make everything a bit more smoother.我现在正在寻找一种让一切变得更顺畅的方法。 I've tried out setting transition: transition: all.3s but this seems not to work.我已经尝试过设置 transition: transition: all.3s但这似乎不起作用。 Any ideas?有任何想法吗?

Use this instead:改用这个:

.checkbox-toggle-wrapper .checkbox-toggle:not(.enabled)::before {
  right: 100%;
  transform: translateX(100%);
}

To make sure you can apply transition to right and transform确保您可以将过渡应用到正确和变换

 jQuery(document).ready(function($) { $(document).on('click', '.checkbox-toggle-wrapper.checkbox-toggle', function() { $(this).toggleClass('enabled'); }) });
 .checkbox-toggle-wrapper { margin-right: 12px; margin-top: 5px; margin-left: 1px; }.checkbox-toggle-wrapper.checkbox-toggle:not(.enabled)::before { right: 100%; transform: translateX(100%); }.checkbox-toggle-wrapper.checkbox-toggle:not(.enabled) { border-color: #999; background-color: #999; }.checkbox-toggle-wrapper.checkbox-toggle { height: 16px; width: 32px; border: 2px solid #00695c; background-color: #00695c; display: inline-block; text-indent: -9999px; border-radius: 10em; position: relative; margin-top: -1px; vertical-align: text-top; cursor: pointer; transition:0.3s all; }.checkbox-toggle-wrapper.checkbox-toggle::before { content: ""; display: block; width: 16px; height: 16px; background: #fff; position: absolute; top: 0; right: 0; border-radius: 100%; transition:0.3s all; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="checkbox-toggle-wrapper"> <span class="checkbox-toggle enabled"></span> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM