我想要动画按钮的宽度时,它的文本更改。我知道我不能使用宽度自动来做这件事。
我的想法基本上是在按钮本身上进行useRef,以获得它的clientWidth,然后更改CSS变量以放置该宽度。然后我将使用该变量来定义宽度。
由于某些原因,宽度设置正确,但动画不起作用。如果我在Chrome开发者工具上编辑CSS,并将宽度从200px改为400px,它就可以工作了……但是,当我将它设置回CSS变量,然后更改内部文本时,即使CSS变量正确更新,动画也无法工作。
.button {
width: var(--buttonwidth);
transition: width 2s ease-in-out;
}// When children(text) changes, update css variable
  useEffect(() => {
    const buttonInnerWidth = buttonRef.current.clientWidth;
    document.documentElement.style.setProperty(
      '--buttonWidth',
      `${buttonInnerWidth}px`
    );
    console.log(buttonInnerWidth);
  }, [children]);有没有人有更好的办法呢?
发布于 2019-08-14 21:49:05
这是一个简单的例子,当点击按钮时改变按钮的宽度。您可以将此监听器更改为任何其他所需的监听器
示例代码:
$(document).ready(function(){
$("button").css({"width":$("button").text().length*10});
  $("button").click(function(){
    var str = " activated ";
    var strWidth = str.length*10;
    $(this).css({"width":strWidth}).text(str);
  });
});button{
height: 40px;
transition: 0.4s;
}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>press</button>
发布于 2019-08-14 22:59:04
这也是另一种方式。几乎与Hooman Namazi的解决方案相同,但方法略有不同。看看这个:
jQuery(function ($) {
		$("button").css({"width":$("button").text().length*10});
    var text = ['first text', 'this is second text', 'and this one is third', 'Hi, I am forth'];
    //used to determine which is the next text to be displayed
    var counter = 0;
    var $button = $('button');
    //repeat the passed function at the specified interval - it is in milliseconds
    setInterval(function () {
        //display the text and increment the counter to point to next text item
        $changeText = $button.text(text[counter++]);
        $button.css({"width":$("button").text().length*10});
        //if it is the last text item in the array point back to the first item
        if (counter >= text.length) {
            counter = 0;
        }
    }, 2000);
})body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}
button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
  transition: 0.5s;
}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>first text</button>
发布于 2019-08-15 16:29:32
我不想使用JS来修复这个性能问题,如果一直检查按钮内文本的宽度就不太好了。当我更改按钮内的文本时,我最终使用width: auto并更改了max-width。
这不是一个完美的解决方案,因为您不能给它提供超长的文本,但对于我的用例来说,它工作得很好:D
这就是了:
.button {
   width: auto;
   white-space: nowrap;
   max-width: 15rem;
   transition: max-width 0.3s cubic-bezier(0.445, 0.05, 0.55, 0.95);
   &.loading {
     max-width: 30rem;
    }
}https://stackoverflow.com/questions/57495206
复制相似问题